Issue
ts
isDayClicked: { [key: number]: boolean } = {};
constructor() { }
setSelectedDay(day: string, index: number): void {
switch (index) {
case 0:
this.isDayClicked[0] = true;
this.isDayClicked[1] = false;
this.isDayClicked[2] = false;
break;
case 1:
this.isDayClicked[0] = false;
this.isDayClicked[1] = true;
this.isDayClicked[2] = false;
break;
case 2:
this.isDayClicked[0] = false;
this.isDayClicked[1] = false;
this.isDayClicked[2] = true;
break;
default:
}
}
html
<ion-col size="4" *ngFor="let d of validDays;let i = index;">
<ion-button expand="block" fill="outline"
[ngClass]="{'active':isDayClicked[i]}" (click)="setSelectedDay(d,i)">
{{d}}
</ion-button>
</ion-col>
css
.active {
background-color: var(--ion-color-primary);
}
UI
I have buttons as shown above. I need to show an active button. So I have used the above trick. But it seems hardcoded thing. i.e. this.isDayClicked[0] = true;this.isDayClicked[1] = false;this.isDayClicked[2] = false;
Do I have a better way to handle this kind of use case?
Note: The above approach is working perfectly fine. But I would like to do it in a better way.
Solution
you can do like this.
create a new variable in your ts file
public selectedIndex = null;
then in your setSelectedDay function change this variable.
setSelectedDay(day: string, index: number): void {
this.selectedIndex = index
}
then in your html do like this.
<ion-col size="4" *ngFor="let d of validDays;let i = index;">
<ion-button expand="block" fill="outline"
[ngClass]="{'active':selectedIndex === i}" (click)="setSelectedDay(d,i)">
{{d}}
</ion-button>
</ion-col>
Let me know if you have any doubt.
Answered By - Piyush Jain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.