Julio Rodríguez
Julio Rodríguez

Reputation: 477

How can I call a function when a someone clicks outside the mat-menu?

I want to run a function every time a user opens a mat-menu and then clicks outside it. How can I detect that the mat-menu is opened and that a click event has occurred outside it? Thanks!

Upvotes: 0

Views: 2735

Answers (2)

Eliseo
Eliseo

Reputation: 57981

Just in button use menuOpened and in mat-menu use closed envent

<button mat-button [matMenuTriggerFor]="menu" (menuOpened)="open()" >Menu</button>
<mat-menu #menu="matMenu" (closed)="close($event)">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

The .ts

  open(){
    console.log("open")
  }
  close(event:any){
    //event is undefined if you click outside
    if (event)
         console.log("click inside the menu")
      else
         console.log("click outside the menu")
  }

see the docs,

Upvotes: 4

Andony Velazquez
Andony Velazquez

Reputation: 11

You can use the @Output menuClosed and menuOpened from matMenuTrigger

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

if you need something more accurate to the events you want to trigger then maybe using @ViewChild you can achieve it I hope this is helpful for you

Upvotes: 1

Related Questions