## Note: ##
onclick of div我正在尝试启用单击的类名。
例如:$('div [data-index ='0.0']')。addClass('selected');在Jquery // addClass中只有指定的div,它有data-index = 0.0。
我不希望它在点击时启用所有className。 启用特定类名的独特方式 我想特别在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.
}
}
先谢谢。!!
答案 0 :(得分:0)
@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}`;
}
};
}
这里的指令将完成你正在寻找的东西,有点矫枉过正,但会帮助你转变为“角度方式”&#34;做事。
要使用上述指令,只需使用此指令调整上面的元素。
<!-- 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>