Home > OS >  How to remove class "show" from previous li in angular?
How to remove class "show" from previous li in angular?

Time:12-20

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 >
    <li  appDropdown></li>
    <li  appDropdown></li>
    <li  appDropdown></li>
    <li  appDropdown></li>
</ul>

CodePudding user response:

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;
    }
  }

CodePudding user response:

I would probably move the responsibility of opening/closing the dropdowns one level higher. Meaning the component that renders the navbar would know the currently open menu, since as I understand you only want to have one open at a time.

Another solution would be to process the arguments of click HostListener, and compare the target to your current nav-item element. If its different, you can remove the class.

  • Related