1

I know this is a frequent question, but this is more related to Angular 5. From what I remember this used to work in Angular 2, unless I specify

changeDetection: ChangeDetectionStrategy.OnPush

Code:

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

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

Did something changed in Angular 5+ that the first method is no longer working?

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

1 Answer 1

2

That's because you're displaying the array in the view using {{ }}. Angular is checking for change in the fruits object. When you push to the array, the reference is the same but in the other method, you changed the reference so it's a new object. Try this in the view :

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

Or you can use json pipe like this :

{{ fruits | json }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.