Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an async list of messages in an angular2 app using angularfire2.

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

When the list updates all elements in the ngFor seem to re-render. Is it possible to just re-render the new items in the list?

like image 293
okhobb Avatar asked Sep 10 '16 16:09

okhobb


2 Answers

The re-rendering happens because you changed the actual reference of an object when data retrieves, that time angular ngFor re draw all the DOM nodes. For such cases you could use trackBy here by which you can make your *ngFor smarter.

trackBy should be based on unique identity column, in your case I could say it would be message.id

<message *ngFor="let message of messages | async;trackBy:trackByFn" [message]="message"></message>

Code

trackByFn(message: any){
   // return message != null ? message.id: null;
   // OR
   return message && message.id; //more better
}
like image 61
Pankaj Parkar Avatar answered Oct 06 '22 11:10

Pankaj Parkar


this is the best solution I have seen.

from @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>
like image 25
Coşkun Deniz Avatar answered Oct 06 '22 13:10

Coşkun Deniz