Angular 5 change detection on mutable objects

I know this is a common question, but it has more to do with Angular 5. From what I remember, it was used to work in Angular 2, unless I specify

changeDetection: ChangeDetectionStrategy.OnPush

the code:

  addFruit(food) {
    // this is not working
    this.fruits.push(food);

    // this works
    // this.fruits = [...this.fruits, food];
  }

Has something changed in Angular 5+ that the first method no longer works?

Working example: https://stackblitz.com/edit/angular-ch-detec?file=app%2Fapp.component.ts

0
source share
1 answer

This is because you are showing the array in the view with {{ }}. Angular checks for change in fruits object. When you click on an array, the link is the same, but in another method you changed the link to become a new object. Try this in a view:

<p *ngFor='let fruit of fruits'>{{ fruit }}</p>

json pipe :

{{ fruits | json }}
+2

Source: https://habr.com/ru/post/1695518/


All Articles