0

I am currently trying to figure out how to automatically refresh the ngFor list when a new object has been pushed to the array. Currently I have the following

component.html

    export class HomePage implements OnInit { 
  collections: Collection[];
  public show = true;
  constructor(){}

  ngOnInit(){
    this.collections = this.collectionList;
  }

  _collections: Collection[] = [
      new Collection('i1', 'Range Rover', 'Model 2019'),
      new Collection('i2', 'Lancer Evolution', 'Model 2008')
    ]

  get collectionList() {
      return [...this._collections];
  }

  addItem(){
    this.testAdd();
  }

  testAdd(){
      this._collections.push(new Collection('i3', 'Chevrolet Camaro', 'Model 2020'));
  }

component.ts

<ion-content>
  <ion-col *ngFor="let col of collections;">
    <div>{{col.title}}</div>
    <div>{{col.description}}</div>
  </ion-col>
  <div style="padding-top:10px;">
        <button type="submit" class="label-center" (click)="addItem()">Add new item</button>
  </div>
</ion-content>

Here's the stackblitz

What am I actually missing?

1 Answer 1

1

The assignment of _collections variable to the collections variable happens only once during ngOnInit.

Pushing a new value to _collections array, makes no difference in the collections array, as its a different copy of the original array and not a referenced version of _collections.

To achieve the expected outcome make the following change:

testAdd(){
      this.collections.push(new Collection('i3', 'Chevrolet Camaro', 'Model 2020'));
  }

Alternate approach :

Using the spread operator returns a new array. If you want to create a reference between _collections array and collectins array then update the get function to

 get collectionList() {
      return this._collections;
  }
Sign up to request clarification or add additional context in comments.

1 Comment

well I overlooked it. Thank you for your explanation

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.