如何防止 DOM 在 angular2 ngFor async 中替换 angularfire2?

How to prevent DOM replacement in angular2 ngFor async in angularfire2?

我在使用 angularfire2 的 angular2 应用程序中有一个异步消息列表。

<message *ngFor="let message of messages | async" [message]="message"></message>

当列表更新时,ngFor 中的所有元素似乎都重新呈现。是否可以只重新呈现列表中的新项目?

重新渲染的发生是因为您在数据检索时更改了对象的实际引用,那时 angular 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
}

这是我见过的最好的解决方案。

来自@jeffbcros

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>