Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which @Input changes in ngOnChanges?

I am using Angular 2.

Right now I have two @input aa and bb. I want to do:

  1. If aa changes, do something.
  2. If bb changes, do other thing.

How to know which @Input changes in ngOnChanges? Thanks

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

  ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    // if aa changes, do something
    // if bb changes, do other thing
  }
like image 822
Hongbo Miao Avatar asked May 24 '16 03:05

Hongbo Miao


1 Answers

Might be able to do it this way

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'm surprised that the unchanged properties are defined, though. From the cookbook, I would expect that only changed properties would be defined.

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

If that is too verbose, you could also try using the setter approach:

_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

like image 130
awiseman Avatar answered Sep 21 '22 11:09

awiseman