我在尝试显示可编辑输入的网格时遇到性能问题。它在大约 200 行和 10 列时开始变得非常慢。 (使用 Angular 4.4)
<tr *ngFor="let row of rows">
<td *ngFor="let column of columns">
<ng-container [ngSwitch]="column.columnType">
<ng-template [ngSwitchCase]="0">
<input [(ngModel)]="row[column.index].value" ...>
</ng-template>
<ng-template [ngSwitchCase]="1">
<select ...>
</ng-template>
<ng-template [ngSwitchCase]="2">
<span ...>
</ng-template>
<ng-template [ngSwitchCase]="...">
<div ...>
</ng-template>
<ng-template [ngSwitchCase]="15">
<a href ...>
</ng-template>
</ng-container>
</td>
</tr>
switch 语句以及 .关于如何减少这种情况的任何想法?
最佳答案
您可能想要使用 trackBy
。您可以将这个额外的部分添加到每个 *ngFor
中,以帮助 Angular 知道每个切片是否需要重绘。它将使用 trackBy
返回的值来确定行是否脏(即 lastTrackByResult === currentTrackByResult
)。
<tr *ngFor="let row of rows; trackBy: rowTrackByFunction">
然后在你的 Controller 中:
rowTrackByFunction(index, item) {
// You will want to return a unique primitive for angular to use as a comparison item
// (string, number, etc.)
return item.someUniqueIdentifier;
}
查看此链接了解更多信息:
https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5
附言如果性能变得非常重要,您可以考虑使用内置虚拟滚动的预制表格组件。我会推荐 NGX-Datable,它可以通过仅绘制用户当前可以看到的内容轻松处理数千行。 http://swimlane.github.io/ngx-datatable/
关于angular - 优化大型 Angular 表格网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50033740/