angularangular-material

How to prevent show mat-menu on click?


I want to show and hide Mat-menu on mouseover and mouseout,but how to prevent show mat-menu on click?

HTML

<button mat-mini-fab color="primary" [matMenuTriggerFor]="menu"
  (mouseenter)="openMenu()">
  <img class="face" *ngIf="isLoginIn()" [src]="faceUrl">
</button>
<mat-menu #menu="matMenu">
  <div (mouseleave)="closeMenu()">
    <button class="login-menu-item" mat-flat-button color="primary">Login</button>
    <button class="login-menu-item" mat-flat-button color="">Logout</button>
  </div>
</mat-menu>

Solution

  • You could use a div instead of a button, then you would just need to get a template reference to the matMenuTrigger to call the open and close methods on your mouseenter and mouseleave events.

    <div mat-mini-fab color="primary" #menuTrigger="matMenuTrigger [matMenuTriggerFor]="menu" (mouseenter)="menuTrigger.openMenu()">
      <img class="face" *ngIf="isLoginIn()" [src]="faceUrl">
    </div>
    <mat-menu #menu="matMenu">
      <div (mouseleave)="menuTrigger.closeMenu()">
        <button class="login-menu-item" mat-flat-button color="primary">Login</button>
        <button class="login-menu-item" mat-flat-button color="">Logout</button>
      </div>
    </mat-menu>
    

    Revision

    Looks like creating a wrapper DIV for the mat-menu and assigning the matMenuTrigger to that wrapper DIV will prevent opening the menu via click on the top MENU DIV.

    <div (mouseenter)="menuTrigger.openMenu()">Menu</div>
    <div #menuTrigger="matMenuTrigger" [matMenuTriggerFor]="menu">
        <mat-menu #menu="matMenu" >
           <div (mouseleave)="menuTrigger.closeMenu()">
              <button mat-menu-item>Item 1</button>
              <button mat-menu-item>Item 2</button>
           </div>
        </mat-menu>
    </div>