In angular 4, I'm using *ngFor to show some images
<div *ngFor='let image of images;let i = index'>
<img [src]="'/assets/Images/'+image+'.png'" *ngIf="!tohide(i,0);">
</div>
After *ngFor is done for the first time, I wish to remove a specific image via *ngIf, without changing the array 'images'. The problem is whenever I removed an image with my function 'tohide', *ngFor bind again to the 'images' and update the set of images.
In other words, is there a way to force *ngFor to not to listen to the array 'images' occasionally?
*ngFor
has a track by function by default, in your case, you want to override it.
<div *ngFor='let image of images;let i = index; trackBy: myTrackByFunction'>
<img [src]="'/assets/Images/'+image+'.png'" *ngIf="!tohide(i,0);">
</div>
In your TS
myTrackByFunction(index, item) {
return index; // or item.id, if your image has an ID
}
For more information, see this web page
u can specify another property i your array named "removed": False and then use this:
<div *ngFor='let image of images;let i = index'>
<img [src]="'/assets/Images/'+image+'.png'" [hidden]="i.removed">
whenever u want to remove an item without really remove it from array just set "removed" property to True.
You can use following as one of the appropriate ways to solve this:
removed
set to false initially. *ngFor
to filter out the images. removed
flag to true. This will filter out the removed image. Edit: the trackBy
is another parameter for *ngFor which you can use instead of developing a separate filter. The filter would give you additional control and features if you need so.
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.