ionic 3中每个元素的类似反应 [英] Like reaction in each element in ionic 3

查看:11
本文介绍了ionic 3中每个元素的类似反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ionic 3,并且像使用 ngFor 一样循环离子卡.我想知道当用户单击每个离子卡中的喜欢/不喜欢"按钮而不重新加载列表时,我该如何与用户做出反应.

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>

推荐答案

您可以使用 *ngIf 运算符.这不会像 hidden 属性那样隐藏元素,但实际上会从 DOM 中删除元素.

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.

(将 u.isLiked 变成 boolean 因为我认为这样更干净,个人喜好.还将 (click) 更改为 <代码>(点击),请参阅 ionic2 点击与点击上的答案a> 了解更多详情.)

(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>

在你的 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;
    }
  }
}

这篇关于ionic 3中每个元素的类似反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆