问题描述
我有一个对象数组(我们叫它arr
).在(change)
方法的组件输入之一中,我修改了这些对象的属性之一,但在视图(*ngFor
)中没有任何变化.我读到Angular2更改检测不检查数组或对象的内容,所以我尝试了这些:
I have an array of objects (let's call it arr
). In one of my component's inputs in the (change)
method I modify one of these object's attribute, but in the view (*ngFor
) nothing changes. I read that Angular2 change detection doesn't check the contents of arrays or object, so I tried these:
this.arr = this.arr.slice();
和
this.arr = [...this.arr];
但是视图没有改变,它仍然显示旧属性.在console.log()
的(change)
方法中,我得到了正确的数组.很奇怪,但是这个可行:this.arr = [];
我也尝试过NgZone
和markForCheck()
.
But the view doesn't change, it still shows the old attribute. In the (change)
method with console.log()
I got the correct array. Weird, but this one works: this.arr = [];
I tried NgZone
and markForCheck()
too.
推荐答案
您还可以在*ngFor
表达式中使用trackBy
选项,为数组中的每个项目提供唯一的ID.这确实使您100%负责更改检测,因此,每次数组中的项目更改时,都要更新此(唯一)属性.然后,只有在数组中的任何项都被赋予了不同的trackBy
属性时,Angular才会重新渲染该列表:
You could also use the trackBy
option in your *ngFor
expression, providing a unique ID for every item inside the array. This does make you 100% responsible for change detection, so update this (unique) property every time the item in the array changes. Angular will then only re-render the list if any item inside your array has been given a different trackBy
property:
*ngFor="let item of (itemList$ | async); trackBy: trackItem"
或:
*ngFor="let item of itemList; trackBy: trackItem"
其中:
trackItem
是组件中的公共方法:
trackItem
is a public method in your component:
public trackItem (index: number, item: Item) {
return item.trackId;
}
这篇关于Angular2:* ngFor在数组更新时不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!