如何知道ngOnChanges中的@Input变化? [英] How to know which @Input changes in ngOnChanges?

查看:197
本文介绍了如何知道ngOnChanges中的@Input变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2.

I am using Angular 2.

现在我有两个@input aabb.我想做:

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

  1. 如果aa发生更改,请执行某些操作.
  2. 如果bb发生更改,请执行其他操作.
  1. If aa changes, do something.
  2. If bb changes, do other thing.

如何知道ngOnChanges中的@Input发生了变化?谢谢

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
  }

推荐答案

可能可以这样做

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

如果这太冗长,您也可以尝试使用setter方法:

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

这篇关于如何知道ngOnChanges中的@Input变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆