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)
但它似乎没有用
您的代码仅将字符串绑定nameOfFuncFromAnotherComponent到callback属性(如果存在,则绑定属性).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澄清:)
小智 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)
| 归档时间: |
|
| 查看次数: |
10699 次 |
| 最近记录: |