Dachstein
Dachstein

Reputation: 4282

Angular 4 - html input element change event triggers @Input() setter with OnPush strategy

I have a simple component:

@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {

  private _items: string[];

  @Input()
  set items(items) {
    console.log('setter of items: ', items); // verify call
    this._items = items;
  }

  onChangeValue(event) {
    console.log('on change value', event);
  }
}

It's template:

<div *ngFor="let item of _items">
  {{item}}
</div>

<input type='text' (change)='onChangeValue($event)'>

Question:
Why the setter @Input() set items(..) is being called after the text has been changed in the input element and the onChangeValue function is called.

I thought Angular's change detection strategy OnPush will trigger the @Input() set items(..) function if and only if the parent component passes in a new reference of items to this component.

However, @Input() set items(..) is also triggered when the input text has changed.

Why??

Upvotes: 1

Views: 1337

Answers (1)

John
John

Reputation: 10069

As explained in this S.O. post:

OnPush is defined this way.

It triggers change detection

  1. when a DOM event the component listens to was received
  2. when the |async pipe receives a new event
  3. when an @Input() was updated by change detection.
  4. when explicitly registering the component to be checked the next change detection turn using ChangeDetectorRef::markForCheck

ChangeDetectionStrategy.Default triggers change detection for every async callback called within Angulars zone (every DOM even listened to within the Angular application, every Observable event or completed Promise, setTimeout, ...)

So, in your case, change detection is being triggered by a DOM event the component listens to.

Upvotes: 1

Related Questions