Change icon type after clicking


#1

I am trying to implement simple like and unlike functionality using one button. If a user already likes that card then it should have a filled red heart icon else just an outline heart icon. My problem is if I click the heart icon it changes all other card heart icons to red. I want to change only the currently clicked one. I tried to use property binding as shown in my code but it is still not working. I understand the problem is caused by the “isliked” variable but I am not sure how to specify only a specific card.

In my template I have the below code

<ion-card *ngFor="let ...>
  <ion-row>
     <ion-col>
      <button ion-button icon-left clear small (click)=" (!current_user_liked || !isliked) ? processLike('like') : processLike( 'unlike')">
        <ion-icon [name]="((current_user_liked ||  isliked) ? 'heart' : 'heart-outline'" </ion-icon>
      </button>
    </ion-col>
  </ion-row>
</ion-card>

In my .ts file, I have the below code.

isliked:boolean = false;
processLike(action){    
    if(action == 'like'){
      this.isliked = true;
    }else if(action == 'unlike'){
      this.isliked = false;
    }
}

Cheers


How to update icon on tabs with custom image from a variable?
#2

Hi,

<ion-card *ngFor="let card of cards”>
  <ion-row>
     <ion-col>
       <button ion-button icon-left clear small (click)="toggleLiked(card)”>
         <ion-icon [name]=“card.icon”</ion-icon>
       </button>
    </ion-col>
  </ion-row>
</ion-card>

You just need to bind a variable to the [name] property and then update the value of that variable:


  cards: CardsInterface[] = [
    { title: 'Card One', name: 'Card1', component: Card-1, icon: 'heart-outline' },
    { title: 'Card Two', name: 'Card2', component: Card-2, icon: 'heart-outline' }
  ];

   ...

  toggleLiked(card: any) {

    if (card.icon === 'heart') {
      card.icon = 'heart-outline';
    } else {
      card.icon = 'heart';
    }
  }

See:

Cheers
Rob


#3

Thank you that was helpful, I had to reorganise my data to resemble your example.


#4

This was the first example I saw that actually worked, and that made sense. Following your lead, I had to do minimal changes to my code. While it did force me to add an extra value to my array, it worked well in the end. So a huge thanks.