首页 > 解决方案 > 单击特定的 ion-item 按钮会触发其他按钮

问题描述

假设数组中有 3 个元素names。因此,下面的 html 将显示 3 个项目,每个项目都附加了单击按钮。

.html

<ion-item *ngFor="let name of names">

   <p>{{name.username}}</p>

   <button ion-button [someAttribute]="isLoad" (click)="clickTest(name.id)">
      Click
   </button>

</ion-item>

.ts

async clickTest(id) {

     isLoad = true;
    // await server side call
    isLoad = false;
}

要求:我只希望特定按钮更改为isLoad = true,而不是所有按钮。 问题:单击Click按钮时,其他按钮也会更改。

标签: ionic-frameworkionic3

解决方案


这与 Javascript 如何处理事件(事件冒泡)有关。

简而言之,您可以这样做:

像这样传递事件并调用 stopPropagation 方法。

.html中

<ion-item *ngFor="let name of names">

   <p>{{name.username}}</p>

   <button ion-button [someAttribute]="isLoad" (click)="clickTest($event, name.id)">
      Click
   </button>

</ion-item>

.ts

async clickTest(event:any, id) {
     event.stopPropagation();

     isLoad = true;
    // await server side call
    isLoad = false;
}

或者,在模板中调用这样的方法:

.html中

<ion-item *ngFor="let name of names">

   <p>{{name.username}}</p>

   <button ion-button [someAttribute]="isLoad" (click)="clickTest(name.id), $event.stopPropagation()">
      Click
   </button>

</ion-item>

推荐阅读