将ngClass添加到所有单击的div中

时间:2018-01-12 16:54:24

标签: angular typescript angular-ng-class

enter image description here

我正在尝试将“active”类添加到单击的所有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);
    }
}

2 个答案:

答案 0 :(得分: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">

答案 1 :(得分:0)

您可以在opt上记录有效状态:

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