How to know which @Input changes in ngOnChanges?

后端 未结 1 579
無奈伤痛
無奈伤痛 2021-02-05 11:00

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
相关标签:
1条回答
  • 2021-02-05 11:49

    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

    0 讨论(0)
提交回复
热议问题