我已经尝试了生命周期挂钩OnChanges,请参见https://angular.io/guide/lifecycle-hooks#onchanges
当Angular(重新)设置数据绑定的输入属性时响应
现在我的问题是:是否可以在更改HTML中其值的非输入属性上触发它? 为什么它不能像下面这样工作?
我有这些文件:
HTML
<html>
<input ([ngModel])="power"></input>
<OnChangesTestComponent [power]="power"></OnChangesTestComponent>
</html>
HtmlComponent:
export class HtmlComponent implements {
power: string;
@ViewChild(OnChangesComponent) childView: OnChangesComponent;
}
OnChangesTestComponent:
export class OnChangesTestComponent implements OnChanges {
@Input() power: string;
ngOnChanges(changes: SimpleChanges) {
...
}
}
我想总结的 :
HTML
<html>
<input ([ngModel])="power"></input>
</html>
HtmlComponent
export class HtmlComponent implements OnChanges {
power: string;
ngOnChanges(changes: SimpleChanges) {
...
}
}
答案 0 :(得分:0)
只要使用一种数据绑定方法就可以在更改值时使视图更新:
//html
<p>{{power}}</p>
//one way databinding to the power variable in your .ts file
//the names in your .ts and html must be the same
要更改该值,应使用BehaviorSubject将“功率”值从输入传递给其他组件。有关https://www.learnrxjs.io/
的更多信息