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

时间:2016-02-12 15:17:42

标签: typescript angular angular2-directives

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

这就是我所拥有的

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

但它似乎无法正常工作

4 个答案:

答案 0 :(得分:8)

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

使Angular管理绑定使用

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

使用此语法,Angular还会计算值

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

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

感谢@MarkRajcok澄清:)

答案 1 :(得分:5)

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

出现一些问题

所以我的建议是做以下

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

<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()
  }
}
相关问题