Ranjeet Avghad
Ranjeet Avghad

Reputation: 387

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.

Upvotes: 0

Views: 747

Answers (1)

user4676340
user4676340

Reputation:

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.

Upvotes: 0

Related Questions