简体   繁体   中英

How to use trackBy on AsyncPipe with images rendering, it re- renders page every time?

My question is how to use trackby on Async pipe with images rendering under it.

I have done following. in html

 <div *ngFor="let friend of friends$ | async;trackBy:trackByFn"> <img [src]="friend.image"> </div> 

and in my component.ts

trackByFn(index, item) {
    if(!item) return null;
    return item && item.id; // or item.id
}

Now problem is that i have a timer of 2 minutes after that i push new elements to friend$ observable using next statement

 this.friends$.next(data);

everytime i do that i can see request for all images. And blink effect on every image why? i am using track by to do not rerender dom elements.

You are pushing a whole new dataset everytime. Try pushing only a new value to your observable, and treat your subject like an array :

friends$ = new BehaviorSubject([]);

add(value) {
  this.friends$.pipe(take(1)).subscribe(items => {
    items.push(value);
    this.friends.next(items);
  });
}

This should automatically resolve your issue, without the need of a track by function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM