1

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>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.