1
votes

Two div elements have values 1 and 2. Every time when each element is clicked I want to toggle css class. This provided solution always toggle css class for both (all) elements.

<div (click)="toggleClass()" [class.active]="isActive">1</div>
<div (click)="toggleClass()" [class.active]="isActive">2</div>

export class MyComponent{
  isActive = false;  
  constructor(){}  
  toggleClass() {
     this.isActive = !this.isActive;
  }
}
1

1 Answers

3
votes
<div (click)="toggleClass(0)" [class.active]="isActive[0]">1</div>
<div (click)="toggleClass(1)" [class.active]="isActive[1]">2</div>

export class MyComponent{
  isActive = [false, false];  
  constructor(){}  
  toggleClass(idx) {
     this.isActive[idx] = !this.isActive[idx];
  }
}

If you want different states for different elements, you need to provide the space (variable) to store that state. Angular isn't magic ;-)

<div (click)="toggleClass(0)" [class.active]="isActive === 0">1</div>
<div (click)="toggleClass(1)" [class.active]="isActive === 1">2</div>

export class MyComponent{
  isActive = -1;  
  constructor(){}  
  toggleClass(idx) {
     this.isActive = idx;
  }
}