Angular2通过属性将函数传递给指令

Angular2 passing a function to a directive via attribute

我正在尝试将父组件中的函数绑定到子组件上的 属性。

这就是我的

@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
    }
}

这就是我的使用方式

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

但是好像不行

您的代码仅将字符串 nameOfFuncFromAnotherComponent 绑定到 callback 属性(如果存在 属性)。 Angular 根本不解释该值。

要使 Angular 管理绑定,请使用

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

使用此语法 Angular 也计算值

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

但在赋值之前将结果转换为字符串(调用.toString())。

感谢@MarkRajcok 的澄清:)

确实没有必要将回调推入@Input 属性。 您可以使用 #local_variable 来提供对子组件的引用。 这样您就可以从父模板访问它的所有属性和方法。 See ng2 documentation on component interaction.

我认为在函数的情况下使用 eventEmitter 要好得多,因为通过引用传递函数会给 this

带来一些问题

所以我的建议是执行以下操作

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()
  }
}

对我来说,这个解决方案有效:

<cm2-component [childFunc]="myFunc.bind(this)"></cm2-component>

import { Output, EventEmitter } from '@angular/core';
export class Cm2 {
  @Input('childFunc') childFunc: Function;
  constructor() { }
  invokeMyFunc(){
    this.childFunc()
  }
}