Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
by (100 points)
+1
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.
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...