Like reaction in each element in ionic 3

情到浓时终转凉″ 提交于 2019-12-08 06:24:05

问题


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>

回答1:


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;
    }
  }
}


来源:https://stackoverflow.com/questions/50602541/like-reaction-in-each-element-in-ionic-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!