Steven Yates Steven Yates - 21 days ago 4x
TypeScript Question

Angular2 passing a function to a directive via attribute

I'm trying to bind a function in a parent component into a property on a child component.

This is what I have

selector: 'awesome',
templateUrl: 'awesome.html'
export class AwesomeComponent {

@Input() callback: Function;

ngOnInit() {

this.callback();//Error, this.callback is not a function, but contains a string value on the fuction call

This is how i'm using it

<awesome callback="nameOfFuncFromAnotherComponent"></awesome>

but it doesn't seem to work


Your code only binds the string nameOfFuncFromAnotherComponent to the callback attribute (and property if it exists). Angular doesn't interpret the value at all.

To make Angular manage the binding use

<awesome [callback]="nameOfFuncFromAnotherComponent"></awesome>

With this syntax Angular also evaluates the value

<awesome callback="{{nameOfFuncFromAnotherComponent}}"></awesome>

but converts the result to a string (calls .toString()) before the assignment.

Thanks to @MarkRajcok for clarification :)