将 ngClass 添加到所有点击的 div

add ngClass to all the divs clicked

我正在尝试将 'active' class 添加到所有单击的 div(在本例中为选项),并在第二次单击时删除 class。

选项计数可能因 ngFor 生成的不同而有所不同。

HTML

<div [ngClass]="{'active': selectedOptions == i}" *ngFor="let opt of options; let i=index"
 (click)="answerSelectedMultiple(i)">

TS

answerSelectedMultiple(index){
    if(this.selectedOptions.indexOf(index) == -1){
        this.selectedOptions.push(index);
    }else{
        this.selectedOptions.splice(this.selectedOptions.indexOf(index), 1);
    }
}

您可以在 opt 上记录活动状态:

<div *ngFor="let opt of options" [ngClass]="{active: opt.active}"
  (click)="opt.active = !opt.active">

您可以将其封装到一个指令中:

@Directive({
  selector: '[activeOnClick]',
  // Optionally replace this both with properties marked 
  // with @HostBinding and @HostListener decorators
  host: {
    '[class.active]': 'clicked',
    '(click)': '_toggle()'
  }
})
export class ActiveOnClickDirective {
   @Input('activeOnClick')
   clicked = false;

   _toggle(){
      this.clicked= !this.clicked;
   }
}

在模块中声明指令后,可以如下使用:

<div activeOnClick *ngFor="let opt of options; let i=index">

如果你想在模板中绑定指令的标志值:

<div [activeOnClick]="true" *ngFor="let opt of options; let i=index">

您甚至可以扩展它以在主机元素上动态应用不同的 类:

@Directive({
  selector: '[classesOnClick]'
})
export class ClassesOnClickDirective { 
   @Input('classesOnClick')
   clicked = false;

   @Input()
   set class(value: string[]| string){
      let classes = Array.isArray(value) ? value : value.split(' ');
      classes = classes.filter(class => !!class);
      this._classes = classes;
   }
   private _classes: string [] = ['active'];

   constructor(private element: ElementRef, private renderer: Renderer2){}

   @HostListener('click')
   _toggle(){
      this.clicked = !this.clicked;
   }

   private _update(){
     this._classes.forEach(class => {
       if(this.clicked){
          this.renderer.addClass(this.element.nativeElement, class);
       }else{
          this.renderer.removeClass(this.element.nativeElement, class);
       } 
     });
   }
}

然后使用如下:

<div [classesOnClick]="true" [classesOnClickClass]="['c1','c2']" *ngFor="let opt of options; let i=index">

<div [classesOnClick]="true" classesOnClickClass="c1 c2" *ngFor="let opt of options; let i=index">