简体   繁体   中英

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; every time I initialzie field2, I want function2() to be called. I guess this is similar to OnInit, but not quite. 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 .

You can can bind each property to a SimpleChange object that exposes new and previous state:

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.
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. 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. For this scenario, implement ngDoCheck and write your own change detection logic inside that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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