htmlangulartypescriptdropdownbootstrap-5

Angular - Why isn't my dropdown list working


HTML code:

<li class="nav-item dropdown pe-3">
  <a class="nav-link nav-profile d-flex align-items-center pe-0" (click)="toggleProfileMenu()">
    <img src="assets/img/profile-img.jpg" alt="Profile" class="rounded-circle">
    <span class="d-none d-md-block dropdown-toggle ps-2">{{ username  }}</span>
  </a>

  <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile" *ngIf="isProfileMenuOpen" (click)="$event.stopPropagation()">
    <li class="dropdown-header">
      <h6>{{username}}</h6>
    </li>
    <li>
      <hr class="dropdown-divider">
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center">
        <i class="bi bi-gear"></i>
        <span>Account Settings</span>
      </a>
    </li>
    <li>
      <hr class="dropdown-divider">
    </li>
    <li>
      <a class="dropdown-item d-flex align-items-center" (click)="logout()">
        <i class="bi bi-box-arrow-right"></i>
        <span>Sign Out</span>
      </a>
    </li>
  </ul>
</li>

ts code:

@Component({
  changeDetection: ChangeDetectionStrategy.Default
})
isProfileMenuOpen = false;
  

  toggleProfileMenu(): void {
    this.isProfileMenuOpen = !this.isProfileMenuOpen;
  }

When I click on that arrow/triangle, nothing happens. (Expected result: The items of the drop list appear and when you click once again they disappear)


Solution

  • Working with Bootstrap, you can work with the data-bs-toggle="dropdown" attribute to expand/collapse the dropdown without the manipulation from Angular (method).

    <a class="nav-link nav-profile d-flex align-items-center pe-0 " href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
        ... 
    </a>
    

    Make sure that you imported the Bootstrap Bundle or Bootstrap + Popper.JS as discussed in Bootstrap 5 dropdown is not working on Angular 12.

    Demo @ StackBlitz