0

在此处输入图像描述

我正在尝试将“活动”类添加到单击的所有 div(在这种情况下为选项)并在第二次单击时删除该类。

选项计数可能因 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);
    }
}
4

2 回答 2

1

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

@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">
于 2018-01-12T17:11:34.593 回答
0

您可以在以下位置记录活动状态opt

<div *ngFor="let opt of options" [ngClass]="{active: opt.active}"
  (click)="opt.active = !opt.active">
于 2018-01-12T17:03:16.373 回答