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

Ste*_*tes 5 typescript angular2-directives angular

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

这就是我所拥有的

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我使用它的方式

<awesome callback="nameOfFuncFromAnotherComponent"></awesome>
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用

Gün*_*uer 8

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

使Angular管理绑定使用

<awesome [callback]="nameOfFuncFromAnotherComponent"></awesome>
Run Code Online (Sandbox Code Playgroud)

使用此语法,Angular还会评估该值

<awesome callback="{{nameOfFuncFromAnotherComponent}}"></awesome>
Run Code Online (Sandbox Code Playgroud)

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

感谢@MarkRajcok澄清:)

  • 由于部件`awesome`已经宣布,`回调="nameOfFuncFromAnotherComponent"一个`callback`输入属性`将字符串`nameOfFuncFromAnotherComponent`结合部件(未属性)的`callback` _property_.这是常量的Angular快捷方式/特殊语法(我不喜欢). (2认同)
  • @StevenYates,`callback ="{{nameOfFuncFromAnotherComponent}}"`将无效,因为它本质上调用`nameOfFuncFromAnotherComponent.toString()`并将其分配给`callback`属性.`{{}}`binding总是指定一个字符串结果. (2认同)

小智 5

我认为,在功能的情况下使用eventEmitter是becouse通过引用传递功能的更多更好会让一些问题与

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

cm1.component.html

<cm2-component (childFunc)="myFunc()"></cm2-component>
Run Code Online (Sandbox Code Playgroud)

cm2.component.ts

import { Output, EventEmitter } from '@angular/core';
export class Cm2 {
  @Output('childFunc') childFunc: EventEmitter<any> = new EventEmitter();
  constructor() { }
  invokeMyFunc(){
    this.childFunc.emit()
  }
}
Run Code Online (Sandbox Code Playgroud)