1

I am using ionic 3, and looping ion-card with like using ngFor. I want to know how can I react with the user when user click the like/unlike button in each ion-card without reload the list.

<ion-card *ngFor="let u of users">
   <p>{{u.name}}</p>
   <button ion-button [hidden]="u.isliked=='1'" (click)="like(u.id)">like</button>
   <button ion-button [hidden]="u.isliked!='1'" (click)="unlike(u.id)">unlike</button>
</ion-card>
Nulra
  • 547
  • 5
  • 19
  • What isn't working in your current code? Or if this code works fine, how do you want to 'react with the user'? – Ivar Reukers May 30 '18 at 10:39
  • @Ivaro18 I can like/unlike, but when I click like button, i need to change to unlike button. If click unlike button, need to change to like button, How can I do this without reload the list? – Nulra May 30 '18 at 10:52

1 Answers1

2

You can make use of the *ngIf operator. This won't hide the element like the hidden property, but actually removes the element from the DOM.

(made u.isLiked into a boolean because I think it's cleaner that way, personal preference. Also changed (click) to (tap), see the answer on ionic2 tap vs click for more details.)

<ion-card *ngFor="let u of users">
   <p>{{u.name}}</p>
   <button ion-button *ngIf="u.isLiked" (tap)="like(u.id)">like</button>
   <button ion-button *ngIf="!u.isliked" (tap)="unlike(u.id)">unlike</button>
</ion-card>

And in your ts:

like(userId) {
  for(let user of this.users) {
    if(user.id == userId) {
        user.isLiked = true;
      }
   }
}

unlike(userId) {
  for(let user of this.users) {
    if(user.id == userId) {
      user.isLiked = false;
    }
  }
}
Ivar Reukers
  • 7,560
  • 9
  • 56
  • 99
  • if users array is very large, will the for loop become a bottle neck? – Nulra May 30 '18 at 11:14
  • You could use `.filter` or another function but the for loop is the fastest way. See https://jsperf.com/extract-props/1 – Ivar Reukers May 30 '18 at 11:18
  • But I'd recommend against loading a very large list of users, you might want to check out ionic's infinite scroll and retrieve your users as a fragmented list. – Ivar Reukers May 30 '18 at 11:19