`ngFor` 创建更多项目

`ngFor` creates more items

我使用 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

If we need at some point to change the data in the collection, Angular needs to remove all the DOM elements that associated with the data and create them again. That means a lot of DOM manipulations especially in a case of a big collection, and as we know, DOM manipulations are expensive.

您可以通过提供 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