可变对象上的Angular 5变化检测 [英] Angular 5 change detection on mutable objects
问题描述
我知道这是一个常见问题,但这与Angular 5有关.根据我的记忆,除非我指定,否则这曾经在Angular 2中起作用
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
代码:
addFruit(food) {
// this is not working
this.fruits.push(food);
// this works
// this.fruits = [...this.fruits, food];
}
在Angular 5+中,第一种方法不再起作用了吗?
Did something changed in Angular 5+ that the first method is no longer working?
工作示例: https://stackblitz.com/edit/angular-ch-detec?file = app%2Fapp.component.ts
推荐答案
这是因为您正在使用 {{}}
在视图中显示数组.Angular正在检查 fruits对象
中的更改.当您推送到数组时,引用是相同的,但是在另一种方法中,您更改了引用,因此它是一个新对象.在视图中尝试:
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>
或者您可以像这样使用 json管道
:
Or you can use json pipe
like this :
{{ fruits | json }}
这篇关于可变对象上的Angular 5变化检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!