简体   繁体   English

Angular: (ngFor) 当我移除一个项目时如何防止它重新加载?

[英]Angular: (ngFor) How to prevent it from reloading when I remove an item?

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? ngFor 指令有什么替代方案吗?

Use trackBy as explained here按照此处的说明使用trackBy

We can help Angular to track which items added or removed by providing a trackBy function.我们可以通过提供 trackBy 函数来帮助 Angular 跟踪添加或删除了哪些项目。 The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item. trackBy 函数将索引和当前项作为参数,并需要返回该项的唯一标识符。 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.现在,当您更改集合时,Angular 可以根据唯一标识符跟踪添加或删除了哪些项目,并仅创建或销毁更改的内容。

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

trackImageId(index: number, picture: PictureModel) {
        return picture.id;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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