Angular2 passing function to directive via attribute

I am trying to bind a function in a parent component to a property of a child component.

This is what I have

@Component({
  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 use it

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

but it does not work

+4
source share
3 answers

Your code only binds a string nameOfFuncFromAnotherComponentto an attribute callback(and a property, if one exists). Angular does not interpret the meaning at all.

To make Angular binding management

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

Angular is also evaluated in this syntax.

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

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

Thanks @MarkRajcok for clarification :)

+6
source

, @Input. #local_variable, . , . . ng2.

+1

I think using eventEmitter in the case of a function is much better, because passing a function by reference will lead to some problems with this

so I suggest doing the following

cm1.component.html

<cm2-component (childFunc)="myFunc()"></cm2-component>

cm2.component.ts

import { Output, EventEmitter } from '@angular/core';
export class Cm2 {
  @Output('childFunc') childFunc: EventEmitter<any> = new EventEmitter();
  constructor() { }
  invokeMyFunc(){
    this.childFunc.emit()
  }
}
+1
source

Source: https://habr.com/ru/post/1628529/


All Articles