Harsha Mullangi
Harsha Mullangi

Reputation: 564

Angular 8 how to hide the dropdown menu when clicking outside the menu

I want to hide the custom dropdown menu when clicking outside the dropdown menu.

I tried the below code but it hides even if i click on a element inside the dropdown menu

<button class="btn btn-primary btn-sm mt-1"  type="button" id="dropdownMenuButton" data-toggle="dropdown" (click)="toggle()" (blur)="toggle()" aria-haspopup="true"
                aria-expanded="false">
                Tools
              </button>

Upvotes: 0

Views: 1256

Answers (2)

Bodhi
Bodhi

Reputation: 200

This can be accomplished by creating an event on the window which toggles the boolean connected to the dropdown if the user clicks somewhere that is not the dropdown/dropdown toggle button, example below:

@ViewChild('dropdown', {static: false}) protected dropdown: ElementRef;
@ViewChild('toggledropdown', {static: false}) protected toggleDropdown: ElementRef;
...
constructor(private renderer: Renderer2, protected router: Router) {
  this.renderer.listen('window', 'click', (e: Event) => {
    if (e.target !== this.dropdown.nativeElement && !this.toggleDropdown.nativeElement.contains(e.target)) {
       this.dropdownOpened = false;
    }
  });
}

The if statement is there to make sure you dont close the dropdown when you click the dropdown or the dropdown toggle element.

Upvotes: 1

Ivan Mihaylov
Ivan Mihaylov

Reputation: 433

Well the (click)="toggle()"

will hide the menu when you click on it and (blur)="toggle()" will hide it when you click outside of it. You decide which action you want to keep on binding to.

Upvotes: 0

Related Questions