Is there a possibility to detect changes only for a specific binding property in angular2?
export class Test{
@Input() a;
@Input() b;
constructor() {
}
ngOnChanges(){
//I want that this only called when a changed
console.log(this.a);
}
}
ngOnChanges triggers following the modification of @Input bound class members. Data bound by the @Input() decorator come from an external source. When the external source alters that data in a detectable manner, it passes through the @Input property again.
When should you use ngOnChanges? Use ngOnChanges whenever you want to detect changes from a variable decorated by @Input. Remember that only changes from the parent component will trigger this function. Also remember that changes from the parent still update the child value even without implementing ngOnChanges.
The ngOnChnages is a life cycle hook, which angular fires when it detects changes to data-bound input property. This method receives a SimpeChanges object, which contains the current and previous property values. The child Component decorates the property using the @Input decorator.
"ngOnChanges" is a lifecycle hook for an Angular component to know when the @Input props are changed. The main drawback of using ngOnChanges is that you have to write much more code to watch a single prop. Angular team also provides another way to intercept the property changes by setter.
As Eric stated, the ngOnChanges
method will be called on every updates of your @Input
s.
If you want to detect only the updates of the @Input
"a" you could use a setter:
export class SubComponent {
@Input()
set a(a:string) {
this._a = a;
console.log('a updated');
}
@Input()
b:any;
(...)
}
See this plunkr: https://plnkr.co/edit/UKyRiq?p=preview.
Use, (You will get both variables value in 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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With