简体   繁体   English

Angular2 Oninit()如何指定要监视的数据绑定属性?

[英]Angular2 Oninit() how to specify data-bound properties to watch for?

For example, I have two input properties: 例如,我有两个输入属性:

@Input() field1;
@Input() field2;

Every time I initialize field1, I want function1() to be called; 每次初始化field1时,我都希望调用function1(); every time I initialzie field2, I want function2() to be called. 每次我初始化field2时,我都希望调用function2()。 I guess this is similar to OnInit, but not quite. 我想这与OnInit相似,但并不完全相同。 Is there any ways to solve the issue? 有什么方法可以解决这个问题吗?

Thanks! 谢谢!

The first time input properties are bound (and every subsequent time thereafeter), the ngOnChanges hook is invoked per the lifecycle documentation . 第一次绑定输入属性(以及随后的每个时间),根据生命周期文档调用ngOnChanges挂钩。

You can can bind each property to a SimpleChange object that exposes new and previous state: 您可以将每个属性绑定到一个公开新状态和以前状态的SimpleChange对象:

ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
  for (let propName in changes) {
    if (propName === 'field1')
      this.function1();

    if (propName === 'field2')
      this.function2();
  }
}

It depends on 这取决于

  • what you mean by "initialize", and 你是什​​么意思“初始化”,和
  • what the types for the two input properties are 两个输入属性的类型是什么

If "initialize" always means assigning a new value, then see @DavidL's answer. 如果“初始化”总是意味着分配一个新值,那么请参阅@ DavidL的答案。
Note that if the input property types are JavaScript reference types (Array, Object, etc.), then "assigning a new value" means assigning a new Array, Object, etc. It does not include modifying an Array item or an Object property. 请注意,如果输入属性类型是JavaScript引用类型(Array,Object等),则“分配新值”意味着分配新的Array,Object等。它不包括修改Array项或Object属性。 Read on for that scenario... 继续阅读该场景......

If the input property types are JavaScript reference types, and "initialize" could mean changing an Array item's value or changing an Object property's value, then ngOnChanges can't be used, since the reference does not change in this scenario, hence Angular change detection does not see this as a change. 如果输入属性类型是JavaScript引用类型,并且“initialize”可能意味着更改Array项的值或更改Object属性的值,则无法使用ngOnChanges ,因为在此方案中引用不会更改,因此Angular更改检测并不认为这是一种变化。 For this scenario, implement ngDoCheck and write your own change detection logic inside that method. 对于这种情况,实现ngDoCheck并在该方法中编写自己的更改检测逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM