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

问题描述 投票:5回答:3

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

这就是我所拥有的

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

但它似乎没有用

typescript angular angular2-directives
3个回答
8
投票

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

使Angular管理绑定使用

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

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

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

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

感谢@MarkRajcok澄清:)


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

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.