1
votes

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;}
1
So what? I works or it doesn't work or whats the problem? Btw, the let i = index; should be inside *ngFor.martin
when i click single button class name added in all button i need specific button to change color like jqueryscript.net/demo/…ganesh sridhar

1 Answers

1
votes

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