Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid image reload in [src] in Angular

I have an app which shows a list of users with a profile picture. When I update a value for this user the image gets reloaded as the observable list emits all data again. How can I avoid this?

<div *ngFor="let user of users">
<img [src]="user.profilepic"/> {{user.name}} <button (click)="updateUser(user)">Update</button>
</div>

TS :

this.userProvider.getUserList()
      .distinct()
      .subscribe(data => {
        this.users = data
      })

I hoped this distinct() function would do the job but no success.. The app is made with ionic 3 in combination with firebase realtime database data and firebase storage pictures downloaded with the public url

EDIT

3 years later I am facing the same issue in another app... Everytime something comes in from my Observable, the images blinks (so I assume it refreshes?)

enter image description here

like image 394
RobrechtVM Avatar asked Jan 30 '18 21:01

RobrechtVM


Video Answer


1 Answers

You need to use trackBy.

<div *ngFor="let user of users; trackBy: trackBy">
    <img [src]="user.profilepic"/> {{user.name}} <button (click)="updateUser(user)">Update</button>
</div>

Then in your component define:

public trackBy(index, user) {
    return user.id; // or any other identifier
}

This will prevent Angular of creating elements in DOM.

like image 187
Vova Bilyachat Avatar answered Sep 29 '22 07:09

Vova Bilyachat