问题
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