是否有可能只检测angular2中特定绑定属性的更改?
export class Test{
@Input() a;
@Input() b;
constructor() {
}
ngOnChanges(){
//I want that this only called when a changed
console.log(this.a);
}
}
答案 0 :(得分:11)
正如Eric所说,ngOnChanges
的每次更新都会调用@Input
方法。
如果您只想检测@Input
“a”的更新,您可以使用setter:
export class SubComponent {
@Input()
set a(a:string) {
this._a = a;
console.log('a updated');
}
@Input()
b:any;
(...)
}
请参阅此plunkr:https://plnkr.co/edit/UKyRiq?p=preview。
答案 1 :(得分:1)
使用,(您将在agrs
中获得两个变量值)
ngOnChanges(...args: any[]) {
console.log('onChange fired');
console.log('changing', args); // so can access both variables here in args.
console.log('changing', args[0]); //a's current and previous value if i'm not wrong.
console.log('changing', args[1]); //b's current and previous value if i'm not wrong.
}
答案 2 :(得分:-1)
ngOnChanges(changes: SimpleChanges): void {
if ('a' in changes) {
// do your thing
}
}