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>
Michael Doye
  • 8,063
  • 5
  • 40
  • 56
glazjoon
  • 518
  • 2
  • 6
  • 15
  • Is closeMenu() being called at all? Try making a function in your component that calls `this.menuTrigger.closeMenu()`, and call that function instead. – Brandon Miller Dec 07 '17 at 14:00

1 Answers1

16

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

Michael Doye
  • 8,063
  • 5
  • 40
  • 56
  • 1
    Until this is officially supported I think this is the best solution. Thank you. – glazjoon Dec 08 '17 at 08:58
  • Can you please update this with an additional functionality so that if I mouseLeave the button itself it turn off the dropdown/menu. – Sami Mar 26 '18 at 14:38
  • 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 Jul 02 '18 at 10:34
  • @Und3rTow on mouseout i need to close the menu can you suggest me. – Vignesh Jul 02 '18 at 11:17
  • this trick works, however if I open mat menu and then do not go inside it, then it will be open forever – Humble Dolt Aug 01 '19 at 06:22
  • @HumbleDolt any findings on your point because i am facing the same issue – Arun Kumar Jan 13 '22 at 07:59