代码之家  ›  专栏  ›  技术社区  ›  Doua Beri

可变对象角度5变化检测

  •  1
  • Doua Beri  · 技术社区  · 8 年前

    我知道这是一个常见的问题,但这与角度5更相关。 从我记忆中可以看出,这在Angular 2中是有用的,除非我指定

    changeDetection: ChangeDetectionStrategy.OnPush
    

    代码:

      addFruit(food) {
        // this is not working
        this.fruits.push(food);
    
        // this works
        // this.fruits = [...this.fruits, food];
      }
    

    角度5+是否发生了变化,第一种方法不再有效?

    工作示例: https://stackblitz.com/edit/angular-ch-detec?file=app%2Fapp.component.ts

    1 回复  |  直到 8 年前
        1
  •  2
  •   Ayman El Temsahi Roevic    8 年前

    这是因为您在视图中使用 {{ }} . Angular正在检查 fruits object . 推送到数组时,引用是相同的,但在另一个方法中,您更改了引用,使其成为新对象。在视图中尝试以下操作:

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

    或者您可以使用 json pipe 这样地:

    {{ fruits | json }}
    
    推荐文章