angular - `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
解决方案
如果我们需要在某个时候更改集合中的数据,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 提高性能
推荐阅读
- html - 3 列中的 div
- node.js - node cron 如何记住它的任务?
- ubuntu - 在 Ubuntu 20.04 LTS 上的 virtualenv 上安装 caffe
- bash - 太多的参数Shell脚本如果检查
- firebase - Firebase 性能监控(角度)
- django - 当我一直在使用“python manage.py test”时,如何在 Django 应用程序中为一个测试用例运行 pytest?
- module - 不合格的断言会在哪些模块中添加术语?
- python - 在使用 python 处理文件之前检查并比较目录/文件夹中的日志文件
- html - 在角度多选选项卡中设置文本
- javascript - 你可以在 PyCharm 社区版中运行 JavaScript 文件吗?