角度2 |具体如何addClass和removeClass(点击div元素激活className)

Angular2 | How to addClass and removeClass specifically (clicked div element to activate the className)

## Note: ##

Onclick of div I am trying to enable the class name which was clicked.

like eg: $('div[data-index='0.0']').addClass('selected'); in Jquery // addClass only to specified div which has data-index =0.0.

I dont want want it to enable all className on click. Unique way of enabling specific class name I want the answer specifically in angular2

    ## Template: ##
    <div  class="board">
          <div  class="matrix selected"  data-index="0-0"  [ngClass]="{selected:isCellSelected}" (click)="fireClickEvent(0-0)">
          </div>
          <div  class="matrix selected"  data-index="0-1" [ngClass]="{selected:isCellSelected}" (click)="fireClickEvent(0-1)">
          </div>
          <div  class="matrix selected"  data-index="1-0" [ngClass]="{selected:isCellSelected}" (click)="fireClickEvent(1-0)">
          </div>
          <div  class="matrix selected"  data-index="1-1" [ngClass]="{selected:isCellSelected}" (click)="fireClickEvent(1-1)">
          </div>
    </div>

    ## component ##
    import { Component, OnInit} from '@angular/core';

    @Component({
      selector: 'app'
    })
    export class displayComponent implements OnInit {

      isCellSelected :boolean ;

      constructor() {
      }

      ngOnInit() {
      }

      fireClickEvent(clickedCell) {
          const selectedCellIndex = clickedCell;
          this.isCellSelected = true; // enabling className for all three
          // I need only clicked cell to activate the className Not all.
      }

    }

Thanks in Advance .!!

@Directive({
  selector: '[selectable]'
})
export class MatrixDirective {
  @HostBinding('class')
  classes = '';

  @Input('selectableClass')
  toggleClass = 'selected';

  @HostListener('click')
  fireClickEvent() {
    if(this.classes.indexOf(this.toggleClass) > -1) {
     this.classes = this.classes.replace(this.toggleClass, '');
    } else {
      this.classes = `${this.classes} ${this.toggleClass}`;
   }
};
}

这里的这个指令将完成您正在寻找的东西,有点矫枉过正,但会帮助您进入 "angular way" 做事。

要使用上述指令,只需使用此指令调整上面的元素即可。

<!-- OLD -->
<div  class="matrix selected"  data-index="0-0"  [ngClass]="{selected:isCellSelected}" (click)="fireClickEvent(0-0)">
      </div>
<!-- Adjusted -->
<div  class="matrix"  data-index="0-0"  selectable>
      </div>