Issue
I have a question, how to remove class "show" from previous li when the user clicks another menu in angular?
I've tried using the directive, but the "show" class still can't be removed from the previous li. This is the directive I have made :
import { Directive, ElementRef, HostListener, Renderer2 } from "@angular/core";
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
manageDropdown : boolean = false;
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
@HostListener('click') openDropdown() {
if(!this.manageDropdown) {
this.renderer.addClass(this.elementRef.nativeElement,'show');
this.manageDropdown = !this.manageDropdown;
} else {
this.renderer.removeClass(this.elementRef.nativeElement, 'show');
this.manageDropdown = !this.manageDropdown;
}
}
}
And here's the appDropdown selector that I call and use in the HTML file
<ul class="navbar-nav">
<li class="nav-item dropdown" appDropdown></li>
<li class="nav-item dropdown" appDropdown></li>
<li class="nav-item dropdown" appDropdown></li>
<li class="nav-item dropdown" appDropdown></li>
</ul>
Solution
You can get the parentElement.childNodes to get the list of all childNode of the parent of the currently clicked element.
Add the below to your openDropdown Hostlistener.
for(let child of this.elementRef.nativeElement.parentElement.childNodes){
this.renderer.removeClass(child, 'show');
}
Final Code:
@HostListener('click') openDropdown() {
for(let child of this.elementRef.nativeElement.parentElement.childNodes){
this.renderer.removeClass(child, 'show');
}
if(!this.manageDropdown) {
this.renderer.addClass(this.elementRef.nativeElement,'show');
this.manageDropdown = !this.manageDropdown;
} else {
this.renderer.removeClass(this.elementRef.nativeElement, 'show');
this.manageDropdown = !this.manageDropdown;
}
}
Answered By - Rohit Goyal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.