How to find out what @Input changes in ngOnChanges?

I am using Angular 2.

Now I have two @input aaand bb. I want to do:

  • If aachanges, do something.
  • If bbchanged, do other things.

How to find out which @Input is changing in ngOnChanges? Thanks

  @Input() aa;
  @Input() bb;

  ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    // if aa changes, do something
    // if bb changes, do other thing
  }
+4
source share
1 answer

You can do it like this.

ngOnChanges(changes: { [propName: string]: SimpleChange }) {
  if( changes['aa'] && changes['aa'].previousValue != changes['aa'].currentValue ) {
    // aa prop changed
  }
  if( changes['bb'] && changes['bb'].previousValue != changes['bb'].currentValue ) {
    // bb prop changed
  }
}

I am surprised that immutable properties are defined. From the cookbook, I would expect that only the changed properties will be defined.

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-on-changes

, setter:

_aa: string;
_bb: string;

@Input() set aa(value: string) {
  this._aa = value;
  // do something on 'aa' change
}

@Input() set bb(value: string) {
  this._bb = value;
  // do something on 'bb' change
}

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter

+10

All Articles