typescript 如何知道 ngOnChanges 中哪些@Input 发生了变化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37404107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:31:03  来源:igfitidea点击:

How to know which @Input changes in ngOnChanges?

typescriptangular

提问by Hongbo Miao

I am using Angular 2.

我正在使用 Angular 2。

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

现在我有两个 @inputaabb. 我想要做:

  1. If aachanges, do something.
  2. If bbchanges, do other thing.
  1. 如果aa发生变化,请做一些事情。
  2. 如果bb发生变化,请做其他事情。

How to know which @Input changes in ngOnChanges? Thanks

如何知道哪个@Input 发生了变化ngOnChanges?谢谢

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

  ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    // if aa changes, do something
    // if bb changes, do other thing
  }

回答by awiseman

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

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:

如果这太冗长,您还可以尝试使用 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

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