How to prevent show mat-menu on click?

Viewed 6585

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>
2 Answers

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>

I did also not want a mat-menu to open on mouse click. I want to solely control it programatically.

I've solved it by applying the css-rule pointer-events: 'none' which tells the HtmlElement to not emit click events if the user interacts with it. As the matMenuTriggerFor directive listens for click events, it will not open.

<div [ngStyle]="{cursor: 'pointer'}">
  <div [matMenuTriggerFor]="menu" [ngStyle]="{'pointer-events': 'none'}">
    <!-- Your Content -->
  </div>
</div>

<mat-menu #menu="matMenu">
  <button mat-menu-item>Foo<button>
  <button mat-menu-item>Bar<button>
  <button mat-menu-item>Baz<button>
</mat-menu>
Related