2
votes

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?

3
What does your tohide() function do? can you post the code of the same - Rohan Kawade
Can't you modify the array before rendering items? - Mike
what is in the tohide() function? - Ashraful Islam
You should mutate your array rather than creating a new array. If you will then Angular will re render the array. Can you paste you ts code here then I can help better. - Sandip Jaiswal

3 Answers

5
votes

*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

1
votes

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.

0
votes

You can use following as one of the appropriate ways to solve this:

  1. You can track remove status of each image object by adding a property called removed set to false initially.
  2. You then implement a filter (as explained here) with *ngFor to filter out the images.
  3. When you remove an image, set the 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!