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

1

2

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>
Atrocity answered 7/12, 2017 at 13:16 Comment(1)
Is closeMenu() being called at all? Try making a function in your component that calls this.menuTrigger.closeMenu(), and call that function instead.Leix
K
17

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

Katleen answered 7/12, 2017 at 14:17 Comment(6)
Until this is officially supported I think this is the best solution. Thank you.Atrocity
Can you please update this with an additional functionality so that if I mouseLeave the button itself it turn off the dropdown/menu.Illusionism
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.Benavides
@Und3rTow on mouseout i need to close the menu can you suggest me.Benavides
this trick works, however if I open mat menu and then do not go inside it, then it will be open foreverDuckweed
@HumbleDolt any findings on your point because i am facing the same issueTransmissible

© 2022 - 2024 — McMap. All rights reserved.