首页 > 解决方案 > `ngFor` 创建更多项目

问题描述

我使用 Angular 10 和*ngFor指令来创建元素列表。每当输入数组发生变化时,我都会对元素做一些事情。例如:

ngAfterViewInit() {
  this.elements.changes.subscribe(t => {
    this.loadElementInfos();
  })
}

如果我break-point在函数内部设置 a ,偶尔我会看到*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

标签: angulardomngfor

解决方案


如果我们需要在某个时候更改集合中的数据,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>

要了解更多信息,请参阅这篇有用的文章:使用 trackBy 提高性能


推荐阅读