Search code examples
javascriptarraysangulartypescriptarray-push

Angular - Refresh array list after a new object being pushed


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?


Solution

  • 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;
      }