Angular - 推送新对象后刷新数组列表

Angular - Refresh array list after a new object being pushed

我目前正在尝试弄清楚如何在将新对象推送到数组时自动刷新 ngFor 列表。 目前我有以下

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>

这是stackblitz

我到底错过了什么?

_collections 变量对 collections 变量的赋值在 ngOnInit 期间仅发生一次。

将新值推送到 _collections 数组,对 collections 数组没有影响,因为它是原始数组的不同副本,而不是 _collections 的引用版本。

为达到预期结果,请进行以下更改:

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

替代方法 :

使用扩展运算符returns 一个新数组。如果要在 _collections 数组和 collectins 数组之间创建引用,请将 get 函数更新为

 get collectionList() {
      return this._collections;
  }