我正在尝试将一个函数数据传递给一个 child ,但是关于 SO 的所有答案都来自 Angular2 in (alfa/beta),我不知道我的问题是否来自于官方发布以来事情已经发生了变化发布。我已经尝试了关于 SO 的所有答案,但它似乎并没有消除我的错误,即“this.bar 不是一个函数”
现在我只是想通过函数传递一个简单的字符串:
父组件:
export class ParentComponent implements OnInit {
foo() {
return "This is a parent func stream value";
}
}
父 HTML
<child [bar]="foo()"></child>
子组件
export class ChildComponent implements OnInit {
@Input() bar : Function;
ngOnInit() {
this.bar();
}
我看不出问题,请帮我看看!
编辑
上面代码中的“Function”类型在我的编辑器中仍然是白色的,这让我很困扰,但是当我像下面的例子一样将代码粘贴到我的组件下面时,相同的“Function”就会变成蓝色,就像我的代码中还有其他类型,所以我想弄清楚为什么会这样……
子组件
export class ChildComponent implements OnInit {
@Input() bar : Function; //The word "Function" here is white when it should be blue
ngOnInit() {
this.bar();
}
}
@Input() bar: Function // This word "Function" is blue like it should be
functionResult: any;
ngOnInit() {
this.functionResult = this.bar();
}
最佳答案
foo()
真的不是一个功能。它评估函数调用的返回值。您的输入bar
期望一个函数作为它的类型。
你应该尝试像<child [bar]="foo"></child>
那样做
编辑
参见 working plunker
关于javascript - Angular2 将函数结果传递给子组件 - "this.bar is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114896/