I am trying to change the background color of the selected item. The items are looped into
Constructor In my constructor, I have the follow.
this.isSelected = false;
Here is the template.
<div>
<ul>
<li *ngFor="let item of items; let i=index">
<span
(click)=onSelect(item)
[ngClass]="isSelected ? 'bg-blue-300': 'bg-red-300'">
{{ item }}
<span>
</li>
</ul>
</div>
In component.ts
I have the following code. Here, I am trying to reset isSelected status to false when an item isn't clicked.
public setIcon(item: string): any {
for( let myItem of this.items){
if(myItem === item){
return this.isSelected = !this.isSelected;
}else {
return this.isSelected = false;
}
}
}
CodePudding user response:
If you want only one item selected at time use a variable "selectedIndex" number
(-1 if no item selected)
selectedIndex:number=-1;
<span
(click)="selectedIndex=selectedIndex==i?-1:i"
[ngClass]="selectedIndex==i? 'bg-blue-300': 'bg-red-300'">
</span>
If you want one or more item selected at time you need declare an array of booleans
selected:boolean[]=[];
<span
(click)="selected[i]=!selected[i]"
[ngClass]="selected[i]? 'bg-blue-300': 'bg-red-300'">
</span>