我在使用 angularfire2 的 angular2 应用程序中有一个异步消息列表。
<message *ngFor="let message of messages | async" [message]="message"></message>
当列表更新 ngFor 中的所有元素时,似乎会重新渲染。是否可以只重新渲染列表中的新项目?
我在使用 angularfire2 的 angular2 应用程序中有一个异步消息列表。
<message *ngFor="let message of messages | async" [message]="message"></message>
当列表更新 ngFor 中的所有元素时,似乎会重新渲染。是否可以只重新渲染列表中的新项目?
发生重新渲染是因为您在数据检索时更改了对象的实际引用,那时角度ngFor
重新绘制了所有 DOM 节点。对于这种情况,您可以trackBy
在此处使用它可以使您*ngFor
更聪明。
trackBy
应该基于唯一的身份列,在你的情况下,我可以说它是message.id
<message *ngFor="let message of messages | async;trackBy:trackByFn" [message]="message"></message>
代码
trackByFn(message: any){
// return message != null ? message.id: null;
// OR
return message && message.id; //more better
}
这是我见过的最好的解决方案。
https://github.com/angular/angularfire2/issues/540#issuecomment-248780730
class MyComponent {
trackFbObjects = (idx, obj) => obj.$key;
}
<message *ngFor="let message of messages | async; trackby: trackFbObjects " [message]="message"></message>