How do I change the style of a single button inside a *ngFor in Ionic 3?

余生颓废 提交于 2020-01-25 07:55:06

问题


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.

Here are my codes:

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

Originally it is like this:

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.


回答1:


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>

Then in your component

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


来源:https://stackoverflow.com/questions/59333638/how-do-i-change-the-style-of-a-single-button-inside-a-ngfor-in-ionic-3

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