如何更改 Ionic 3 中 *ngFor 内单个按钮的样式?

2022-01-21 00:00:00 css ionic-framework ionic3 angular sass

我正在尝试更改我在 ion-col 中的 *ngFor 中单击的特定按钮的样式.目前当我点击一个按钮时,所有按钮的样式都会同时改变.

I am trying to change the style of the specific button I click in the *ngFor in the ion-col. Currently when I click on a button, the styles for all buttons changes at the same time.

这是我的代码:

<ion-col *ngFor="let item of displayRestaurant[0].seatTimeSlotAndDiscount | slice:indexStart:indexEnd; let i=index" no-padding>
  <button ion-button style="border-radius:100px;height:70px;width:70px;text-align:center;" (click)="clickedDiscount(item)"  [ngClass]="clickedDiscountBoolean ? 'discountClicked' : 'discountUnclicked'">
    <p style="font-size: 10px; color:white;">{{item.percentageDiscount}}</p>
    <p style="font-size:10px;color:white;">{{item.timeOfDiscount}}</p>
  </button>
</ion-col>

SCSS:

.discountClicked{
    border: 3px solid orange;
}

.discountUnclicked{
    border:none;
}

.ts:

clickedDiscount(discount:Discount){
  this.clickedDiscountBoolean = !this.clickedDiscountBoolean;
}

原来是这样的:

这是我单击任何按钮后当前代码所做的事情(新样式适用于所有按钮):

Here is what my current codes do after I clicked on any of the buttons (The new style is applied to all):

我正在寻找的是,当我点击任何按钮时,只有那个按钮的样式会改变,其余的都不会.

What I am looking for is, when I click on any of the buttons, only that button's style will change, and the rest will not.

推荐答案

你所有的按钮都会查找相同的条件.您只需要将这个条件统一为一个按钮即可.您可以为此使用索引值:

All your buttons look up for same condition. You need to unify that condition to be true for only one button. You can use index value for that :

<ion-col *ngFor="let item of displayRestaurant[0].seatTimeSlotAndDiscount | slice:indexStart:indexEnd; let i=index" no-padding>
  <button ion-button style="border-radius:100px;height:70px;width:70px;text-align:center;" 
      (click)="clickedDiscount(item,i)"  
      [ngClass]="clickedIndex ===  i ? 'discountClicked' : 'discountUnclicked'">
    <p style="font-size: 10px; color:white;">{{item.percentageDiscount}}</p>
    <p style="font-size:10px;color:white;">{{item.timeOfDiscount}}</p>
  </button>
</ion-col>

然后在你的组件中

clickedDiscount(discount:Discount,index:number){
  this.clickedIndex = index;
}

相关文章