Change an icon on click in ngFor

Hi. How to change a selected icon inside ngFor on click. i tried using ngclass, but it ended up in changing all the icons in the loop. Please help

Could you share what you have tried?

Hi. I do something like this in my current app. My app displays some subjects on screen and the user selects and de-selects them. On each line to the left of each subject title is an icon which changes when you select and de-select. In my HTML I have:

<ion-list no-lines>
    <ion-item *ngFor="#subject of subjects; #i=index" (click)="clickSubject(i)">
      <ion-avatar item-left>
        <img [src]="subject.selected?subject.whiteIcon:subject.colouredIcon">
      </ion-avatar>
      <h2>{{subject.name}}</h2>
    </ion-item>
  </ion-list>

and in my component I do:

clickSubject(index) {
    // user clicked on a subject - are they selecting or de-selecting?
    if(this.subjects[index].selected == false) {
      this.selectSubject(index);
    } else {
      this.deSelectSubject(index);
    }
  }

I haven’t shown the selectSubject and deSelectSubject methods but they just maintain the array of selections.

Thanks for the reply @mhartington and @richardshergold, It worked now. I missed to include “” for my icon name in conditional statement. Thanks again :slightly_smiling:

1 Like

hi richard! i know it’s an old post
but can you show me your selectsubject and deselect method?
Thanks!