如何在Angular中优化渲染?

时间:2019-04-19 10:46:12

标签: angular

我使用 ngFor 在模板中渲染对象数组:

self.button = wx.Button(id = -1,label='No. of Targets',parent=self.panel1, size=wx.Size(100, 30), style=wx.TEXT_ALIGNMENT_LEFT)

当数组<tr *ngFor="let p of rows; let i = index"> <td class="tableDefault__td tableDefault__center td__number"> {{ i + 1 }} </td> <td class="tableDefault__td tableDefault__center td__date"> <div class="history_item" *ngFor="let h of p.history"> <span class="span_link" (click)="goto(h)" >{{ h.classNumber }}{{ h.classSuffix }}, {{ formatDate(h.whenDate) }}</span > </div> </td> <td class="tableDefault__td tableDefault__center td__theme"> <input [disabled]="!isOwner(teacherId)" type="text" name="subject" placeholder="{{ 'create_plan_e_name' | translate }}" [(ngModel)]="p.topic" autofocus /> </td> </tr> 容纳400个以上的对象时,渲染工作非常缓慢。如何优化渲染或缓存?也许问题出在嵌套循环rows中?

1 个答案:

答案 0 :(得分:3)

您可以在trackBy指令中使用ngFor函数,通过提供唯一的ID来提高性能。它使Angular可以更好地处理与绑定数组有关的更改检测。

类似的东西:

HTML

<tr *ngFor="let p of rows; trackBy: trackByFunction; let i = index">
    ....
</tr>

TS

public trackByFunction(index, item) {
    if (item) {
        return item.id;
    }
    return null;
}

example很好。

还有官方documentation