How to make Material Design Menu (mat-menu) hide on mouseleave

17,794

You can do this by wrapping the menu buttons in a <span> element:

HTML:

<button mat-button 
  [matMenuTriggerFor]="menu" 
  (mouseenter)="openMyMenu()">
  Trigger
</button>
<mat-menu #menu="matMenu" overlapTrigger="false">
  <span (mouseleave)="closeMyMenu()">
    <button mat-menu-item>Item 1</button>
    <button mat-menu-item>Item 2</button>
  </span>
</mat-menu>

Component:

export class MenuOverviewExample {
  @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;

  openMyMenu() {
    this.trigger.openMenu();
  } 
  closeMyMenu() {
    this.trigger.closeMenu();
  }  
}


Demo (V5):

StackBlitz

Material V6:

StackBlitz

Share:
17,794
glazjoon
Author by

glazjoon

Updated on June 14, 2022

Comments

  • glazjoon
    glazjoon about 2 years

    I succeeded in making the menu appear on mouseenter. What I want to do now is make it disappear on the mouseleave event of the menu itself. Any ideas on how to make this possible?

        <button mat-button [mat-menu-trigger-for]="menu" 
         #menuTrigger="matMenuTrigger" (mouseenter)="menuTrigger.openMenu()">
            TRIGGER BUTTON
        </button>
        <mat-menu #menu="matMenu" [overlapTrigger]="false" 
         (mouseleave)="menuTrigger.closeMenu()">
             <button mat-menu-item [routerLink]="['sources']">
                  <mat-icon>view_headline</mat-icon>
                  MENU CHOICE
            </button>
        </mat-menu>
    
    • Brandon Miller
      Brandon Miller over 6 years
      Is closeMenu() being called at all? Try making a function in your component that calls this.menuTrigger.closeMenu(), and call that function instead.
  • glazjoon
    glazjoon over 6 years
    Until this is officially supported I think this is the best solution. Thank you.
  • Sami
    Sami over 6 years
    Can you please update this with an additional functionality so that if I mouseLeave the button itself it turn off the dropdown/menu.
  • Vignesh
    Vignesh almost 6 years
    This (mouseleave) event is not working for latest version of the packages. So can you make the require changes for the latest version of the packages.
  • Vignesh
    Vignesh almost 6 years
    @Und3rTow on mouseout i need to close the menu can you suggest me.
  • Humble Dolt
    Humble Dolt almost 5 years
    this trick works, however if I open mat menu and then do not go inside it, then it will be open forever
  • Arun Kumar
    Arun Kumar over 2 years
    @HumbleDolt any findings on your point because i am facing the same issue