仅在单击的元素上切换css类

时间:2017-10-30 13:26:27

标签: angular

两个div元素的值为1和2.每次单击每个元素时,我都要切换css类。 这提供的解决方案总是为两个(所有)元素切换css类。

<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 个答案:

答案 0 :(得分:3)

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

如果您想要不同元素的不同状态,则需要提供空间(变量)来存储该状态。角度不是魔法; - )

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