Doctor Robot
Doctor Robot

Reputation: 49

Hide Collapse Menu & Toggle Menu in Angular

I found a problem, how do I do that when the user clicks on one of the dropdown menus on the mobile, it will close the previous dropdown menu and open the clicked menu? Then when the user click a menu inside the dropdown, it will close all dropdown menus including the toggle menu?

Here's the code I have

ngOnInit(): void {
    if ($(window).width() < 991.98) {
      document.querySelectorAll('.nav-item').forEach(function(element){
        element.addEventListener('click', function (this: any, e) {
          let nextEl = this.nextElementSibling;

          if(nextEl && nextEl.classList.contains('dropdown-menu')) {
            e.preventDefault();
            if(nextEl.style.display == 'block'){
              nextEl.style.display = 'none';
              nextEl.style.opacity = '0';
              nextEl.style.position = 'relative';

              $(this).closest('li').removeClass('active');
            } else {
              nextEl.style.display = 'block';
              nextEl.style.opacity = '1';
              nextEl.style.position = 'relative';

              $(this).closest('li').addClass('active');
            }
          }
        });
      })
    }
  }
    collapse() {
        this.showMenu = !this.showMenu;
        var toggle;
    
        if (this.showMenu == true) {
            toggle = this.elRef.nativeElement.querySelector('.toggle-menu');
            toggle.classList.add('active');
    
            $('.header-area .nav').slideToggle(200);
        } else {
            toggle = this.elRef.nativeElement.querySelector('.toggle-menu');
            toggle.classList.remove('active');
    
            $('.header-area .nav').slideToggle(200);
        }
    }

index.html

<ul class="nav">
  <li>
    <a class="nav-item">Home</a>
    <div class="dropdown-menu">
      <a routerLink="/home" class="dropdown-item">Home</a>
      <a routerLink="/dashboard" class="dropdown-item">Dashboard</a>
      <a routerLink="/setting" class="dropdown-item">Setting</a>
    </div>
  </li>
  <li>
    <a class="nav-item">Explore</a>
    <div class="dropdown-menu">
      <a routerLink="/user" class="dropdown-item">User</a>
      <a routerLink="/admin" class="dropdown-item">Admin</a>
    </div>
  </li>
</ul>
<a class="toggle-menu" (click)="collapse()">
<span>Menu</span>
</a>

Upvotes: 1

Views: 693

Answers (1)

Phong Cao
Phong Cao

Reputation: 33

First, I would say that you should not using JQuery and some basic Javascript document query syntaxs in Angular. Angular is not working like this.

Second, about the dropdown, thinking more simple, you need to determine which button was pressed, add class "active" if it not already there, and remove from all remaining

Upvotes: 1

Related Questions