Reputation: 1691
I have a directive that should make list element to be red color on click. It is working as expected but it should also Turn to black when other li is clicked so only the selected li should be in red color
Here is my implementation,
@HostListener('click', ['$event']) clickedInside(event) {
event.preventDefault();
event.stopPropagation();
this.removeBorder();
this.setElementStyleToBold();
if (this.el.nativeElement.contains(event.target)) {
this.clicked = event.target.id;
}
}
Here is another host listener that watch the click outside and change the color to black when clicked on the document,
@HostListener('document:click', ['$event']) clickedOutside(event){
event.preventDefault();
event.stopPropagation();
this.removeBorder();
}
In the clickedInside function I am calling remove border function before calling setElementStyleToBold function so it will remove the black color and red color is applied only on the selected item.
This is not working as intended and I don’t know where I was wrong Here is my code on stackblitz
Upvotes: 1
Views: 500
Reputation: 680
You can create new method with below code
private removeColor() {
document.querySelectorAll('[appSelectedItem]').forEach((el) => {
this.removeBorder(el);
})
}
and call that instead of this.removeBorder();
in clickedInside
method like this
@HostListener('click', ['$event']) clickedInside(event) {
event.preventDefault();
event.stopPropagation();
this.removeColor();
this.setElementStyleToBold();
if (this.el.nativeElement.contains(event.target)) {
this.clicked = event.target.id;
}
}
Upvotes: 1