Angular: (ngFor) How to prevent it from reloading when I remove an item?
Asked Answered
G

1

7

I have a list of images in my page:

<img *ngFor="let picture of pictures" [src]="picture.path">

The problem is that, every time I remove a picture, the previous list is recreated and all the images are reloaded. How can I prevent it from reloading the images when I remove an item? Is there any alternative for the ngFor directive?

Gallon answered 21/2, 2018 at 12:37 Comment(3)
mmm, if the paths are the same after list regeneration, shouldn't the images be cached?Millen
You are most probably returning a complete list after deleting an item, instead of just removing an item from the existing list. That way it will not recreate.Apeak
The images are loaded from an external service. I'll try the "trackBy" option to see if I can improve the performance.Gallon
H
8

Use trackBy as explained here

We can help Angular to track which items added or removed by providing a trackBy function. The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item. Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.

<img *ngFor="let picture of pictures; trackBy: trackImageId" [src]="picture.path">

trackImageId(index: number, picture: PictureModel) {
        return picture.id;
    }
Huntsville answered 21/2, 2018 at 12:47 Comment(4)
This is amazing. It works like a charm. I don't understand why my question has so many downvotes. I guess this is a trivial question for most of people.Gallon
Happy it helped ! I think you're getting downvoted because you are asking for an "alternative" instead of searching the framework documentation.Huntsville
Hey, what purpose does index:number serve in the function? Why is picture.id being returned? Should that be called picture.index?Diplomacy
@Gallon FWIW, now you have one more upvote :)Dividers

© 2022 - 2024 — McMap. All rights reserved.