Angular: (ngFor) 当我删除一个项目时如何防止它重新加载?
Angular: (ngFor) How to prevent it from reloading when I remove an item?
我的页面中有图片列表:
<img *ngFor="let picture of pictures" [src]="picture.path">
问题是,每次我删除图片时,都会重新创建之前的列表并重新加载所有图片。删除项目时如何防止它重新加载图像? ngFor 指令有任何替代方案吗?
按照说明使用 trackBy
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;
}
我的页面中有图片列表:
<img *ngFor="let picture of pictures" [src]="picture.path">
问题是,每次我删除图片时,都会重新创建之前的列表并重新加载所有图片。删除项目时如何防止它重新加载图像? ngFor 指令有任何替代方案吗?
按照说明使用 trackBy
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;
}