Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
well, this solution is good, however there is a bug. if you click the button,  open the menu and not hover over menu, you can close it with no changes for the button. If my button has an extra class to show that this button is active, it is a problem then.
thumb_up_alt 1 thumb_down_alt 0
Welcome to 16892 Developer Community-Open, Learning and Share
...