【问题标题】:How to prevent DOM replacement in angular2 ngFor async in angularfire2?如何防止 Angular2 中的 DOM 替换 ngFor async 在 angularfire2 中?
【发布时间】:2017-01-18 14:16:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

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

    【讨论】:

    • 不应该是trackBy:trackByFn而不是trackBy= trackByFn吗?
    • @GünterZöchbauer 感谢您的提醒,我错过了 :)
    • @GünterZöchbauer 是的。固定。
    • 谢谢。这并不完全有效,但是 其中 trackByFn 返回了 id。
    • 我认为第一个参数是索引。如果要使用自己的 id,则需要第二个参数。 trackByFn(index, item) { return (item) ? item.id:未定义; }
    【解决方案2】:

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

    来自@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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2018-04-30
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      相关资源
      最近更新 更多