Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2- ngOnChanges only for a specific binding

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);
     }
}
like image 539
muetzerich Avatar asked Mar 17 '16 13:03

muetzerich


People also ask

What triggers ngOnChanges?

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 we use ngOnChanges in Angular?

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.

How does ngOnChanges work in Angular?

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.

Is ngOnChanges required?

"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.


2 Answers

As Eric stated, the ngOnChanges method will be called on every updates of your @Inputs.

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.

like image 195
Thierry Templier Avatar answered Oct 13 '22 11:10

Thierry Templier


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.
 }
like image 25
Nikhil Shah Avatar answered Oct 13 '22 10:10

Nikhil Shah