我使用Angular 10和*ngFor
指令创建元素列表。每当输入数组更改时,我都会对该元素进行操作。例如:
ngAfterViewInit() {
this.elements.changes.subscribe(t => {
this.loadElementInfos();
})
}
如果我在函数内部设置了break-point
,偶尔会发现*ngFor
实际上将新元素添加到列表中,然后丢弃了旧元素。
例如:
old-element-0
old-element-1
old-element-2
old-element-3
new-element-0
new-element-1
new-element-2
new-element-3
一毫秒后,旧元素将被丢弃。有没有机会控制ngFor
的行为以使其不这样做?
new-element-0
new-element-1
new-element-2
new-element-3
答案 0 :(得分:4)
如果我们需要在某个时候更改集合中的数据,则Angular需要删除与以下内容关联的所有
DOM
元素 数据并再次创建它们。这意味着很多DOM
操作,尤其是在有大量收藏的情况下,以及 知道DOM
的操作很昂贵。
您可以通过提供以下trackBy
函数来帮助Angular跟踪添加或删除的项目:
app.component.ts
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `./my-app.html`,
})
export class App {
collection = any[];
constructor() {
this.collection = [{id: 1}, {id: 2}, {id: 3}];
}
trackByFn(index, item) {
return index;
}
}
app.component.html
<ul>
<li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
</ul>
要了解更多信息,请参阅此有用的文章: Improve Performance with trackBy