Javascript 输入变化时的Angular2调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39331125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:29:12 来源:igfitidea点击:
Angular2 Call Function When the Input Changes
提问by Bünyamin Sar?gül
Child component:
子组件:
export class Child {
@Input() public value: string;
public childFunction(){...}
}
Parent component:
父组件:
export class Parent {
public value2: string;
function1(){ value2 = "a" }
function2(){ value2 = "b" }
}
Parent view:
父视图:
<child [value]="value2">
Is there any way to call childFunction() every time the value2 is changed in this structure?
每次更改此结构中的 value2 时,有没有办法调用 childFunction()?
回答by Günter Z?chbauer
You can use the ngOnChanges()
lifecycle hook
您可以使用ngOnChanges()
生命周期钩子
export class Child {
@Input() public value: string;
ngOnChanges(changes) {
this.childFunction()
}
public childFunction(){...}
}
or use a setter
或使用二传手
export class Child {
@Input()
public set value(val: string) {
this._value = val;
this.childFunction();
}
public childFunction(){...}
}