Issue
I have one table with rows. When I click on a cell it has changed color to red but only one at a time can be red. If I click on another cell, the previous cell should no longer be red. I don't know how to make only one cell red at a time. Do you have any ideas?
html file:
<table>
<tr appFocusCell><td > </td></tr>
<tr appFocusCell><td> </td></tr>
<tr appFocusCell><td> </td></tr>
<tr appFocusCell><td> </td></tr>
<tr appFocusCell><td> </td></tr>
<tr appFocusCell><td> </td></tr>
<tr appFocusCell><td></td></tr>
</table>
focus-cell.directive file:
import {Directive, ElementRef, HostListener, Renderer2} from '@angular/core';
@Directive({
selector: '[appFocusCell]'
})
export class FocusCellDirective {
constructor(private e:ElementRef,private render: Renderer2) { }
ngOnInit() {
}
@HostListener('click')
onClick(){
const div = this.e.nativeElement;
this.render.setStyle(div,'background','red')
}
}
Solution
Following is the code sample
html
<table border="1">
<tbody>
<tr>
<td appCellClick>
Cell1.1
</td>
<td appCellClick>
Cell1.2
</td>
</tr>
<tr>
<td appCellClick>
Cell2.1
</td>
<td appCellClick>
Cell2.2
</td>
</tr>
</tbody>
</table>
directive
import { Directive, HostListener, Renderer2 } from '@angular/core';
@Directive({
selector: '[appCellClick]',
})
export class CellClickDirective {
@HostListener('click', ['$event']) onClick(ev) {
const curEl = ev.target; //TAKE CLICKED CELL ELEMENT
let parentEl:any = {};
// CHECK THE PARENT TABLE ELEMENT
const parentChecker = (el) => {
if (el.nodeName == 'TABLE') {
parentEl = el;
} else {
parentChecker(el.parentElement);
}
};
parentChecker(curEl);
// PARENT TABLE FOUND - REMOVE EXISTING CSS-CLASS
if(parentEl){
const addedBg = parentEl.querySelectorAll('td.bg-red');
addedBg.forEach((e) => {
e.setAttribute('class', e.getAttribute('class').replace('bg-red',''));
});
}
this.renderer.addClass(curEl, 'bg-red');
}
constructor(
private renderer: Renderer2
) {}
}
css
.bg-red{
background-color: red;
}
Answered By - Nathash Kumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.