优化大角度表格

gee*_*jay 7 performance angular

尝试显示可编辑输入网格时遇到性能问题.它开始变得非常慢,大约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>
Run Code Online (Sandbox Code Playgroud)

在switch语句中还有很多时间(根据Chrome分析器 - debugUpdateDirectives).关于如何减少这个的任何想法?

Pea*_*man 5

您可能想要使用trackBy.您可以将这个额外的部分添加到每个部分,*ngFor以帮助Angular知道是否需要重新绘制每个切片.它将使用返回的值trackBy来确定该行是否为脏(即lastTrackByResult === currentTrackByResult).

<tr *ngFor="let row of rows; trackBy: rowTrackByFunction">
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

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;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此链接:

https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

PS如果性能变得非常重要,您可以考虑使用内置虚拟滚动的预制表组件.我建议使用NGX-Datable,只需绘制用户当前可以看到的内容即可轻松处理数千行. http://swimlane.github.io/ngx-datatable/