0

I've got a dropdown menu in my navbar which I open and close by adding a show class to it when clicked.

This works but requires the user to click the button again to close the menu. As a semi-solution I now listen for router changes and close the menu whenever the route changes.

However I'd like the menu to close if anything except the menu button is clicked. So that users can click the background to get rid of the menu. How do I achieve this?

<button class="btn btn-link nav-link dropdown-toggle" (click)="showDropdown=!showDropdown" id="navbarDropdown" role="button" >

<div class="dropdown-menu" [ngClass]="{'show': showDropdown}">

Please don't offer solutions with jquery. I am not using it in this project.

charsi
  • 2,917
  • 22
  • 40

1 Answers1

1

You can do this listening the mouseout event on your dropdown menu and setting the variable showDropdown to false. I mean:

<button class="btn btn-link nav-link dropdown-toggle" (click)="showDropdown=!showDropdown" id="navbarDropdown" role="button">

<div class="dropdown-menu" [ngClass]="{'show': showDropdown}" (mouseout)="showDropdown = false"> <!-- This --!>

Hope can help!!!

OPulido
  • 309
  • 2
  • 10
  • Hey this does work. But I don't want the menu to disappear as soon as the mouse moves away but when something else or even the background is clicked. – charsi Feb 05 '18 at 04:26
  • So you can change mouseout by (blur)="showDropdown = false" and set tabindex="-1" . I mean – OPulido Feb 05 '18 at 05:26
  • This helped.. https://stackoverflow.com/questions/35712379/how-can-i-close-a-dropdown-on-click-outside – charsi Feb 05 '18 at 05:26