【问题标题】:`ngFor` creates more items`ngFor` 创建更多项目
【发布时间】:2020-09-09 21:38:48
【问题描述】:

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

【问题讨论】:

  • 确实取决于您在该函数中执行的操作以及对象的外观,但通常您可以使用trackBy 子句进行控制

标签: angular dom ngfor


【解决方案1】:

如果我们需要在某个时候更改集合中的数据,Angular 需要删除所有与 数据并再次创建它们。这意味着很多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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2019-05-22
    • 2016-09-23
    • 2012-12-01
    • 1970-01-01
    相关资源
    最近更新 更多