Reputation: 45
I'm running into a problem with add class name based on the Angular 2 ngFor loop index. using ngFor creating multiple button, when i click button add class in the specific button. like tag select For your reference Link
<button color="light" *ngFor="let category of categories" [class.tagactive]='stateOfButton' (click)="changeState(i)" let i = index;>{{category}} <span (click)="delete(i)">X</span></button>
stateOfButton: boolean = false;
categories = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado', 'mango'];
changeState(index) {
this.stateOfButton = !this.stateOfButton;
}
delete(index) {
this.categories.splice(index, 1);
}
.tagactive { background: #cc3333; color:#fff;}
Upvotes: 1
Views: 1963
Reputation: 13558
You need array
to manage active or inactive state of button :
//HTML
<button color="light" *ngFor="let category of categories;let i = index;" [class.tagactive]="stateOfButton[i]" (click)="changeState(i)">{{category}} <span (click)="delete(i)">X</span></button>
// Component
categories = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado', 'mango'];
stateOfButton: boolean[];
ngOnInit() {
// Creates the array with inactive state initially for all category items.
this.stateOfButton = Array(this.categories.length).fill(false);
}
changeState(index) {
this.stateOfButton[index] = !this.stateOfButton[index];
}
delete(index) {
this.categories.splice(index, 1);
this.stateOfButton.splice(index, 1);
}
Upvotes: 1