Angular 这种方法能跟踪子组件中@input变量的变化吗?
父组件Angular 这种方法能跟踪子组件中@input变量的变化吗?,angular,typescript,rxjs,observable,Angular,Typescript,Rxjs,Observable,父组件父组件和子组件子组件,父组件将值传递给其子组件 <child childInputValue="value"> </child> 不,不行childInputValue$将只具有初始值,并且永远不会更新 正如您所提到的,您可以使用ngOnChanges进行跟踪 还可以使用get/set: private _childInputValue: any; @Input() set childInputValue(value: any) { this._chil
父组件和子组件子组件,父组件将值传递给其子组件
<child childInputValue="value"> </child>
不,不行childInputValue$
将只具有初始值,并且永远不会更新
正如您所提到的,您可以使用ngOnChanges
进行跟踪
还可以使用get/set
:
private _childInputValue: any;
@Input()
set childInputValue(value: any) {
this._childInputValue = value;
//childInputValue changes, do something here
}
get childInputValue(): any {
return this._childInputValue;
}
或
childInputValue$=新行为主体(空);
childInputValue$.subscribe(()=>{
//childInputValue更改,请在此处执行操作
})
@输入()
设置childInputValue(值:任意){
this.childInputValue$.next(值);
}
get childInputValue():任意{
返回此.childInputValue$.getValue();
}
这里的行为主体
是用初始值未定义的
声明的,因为childInputValue
是未定义的
。除非使用childInputValue$.next('value')
推送一个新值,否则订阅不会发出任何内容。感谢您的输入@MichaelD。这很有道理,我很困惑,如果这样做有效,为什么我们需要ngOnChanges,但现在我知道为什么了。哦,我不知道这种get/set方法。谢谢你的建议,你的回答让一切都清楚了。我将把这个标记为已接受。
private _childInputValue: any;
@Input()
set childInputValue(value: any) {
this._childInputValue = value;
//childInputValue changes, do something here
}
get childInputValue(): any {
return this._childInputValue;
}
childInputValue$ = new BehaviourSubject<any>(null);
childInputValue$.subscribe(() => {
//childInputValue changes, do something here
})
@Input()
set childInputValue(value: any) {
this.childInputValue$.next(value);
}
get childInputValue(): any {
return this.childInputValue$.getValue();
}