Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Mat Menu disable matMenuTriggerFor

I have the following material menu:

<a mat-button [matMenuTriggerFor]="menu" disabled="true">Menu</a>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

Notice that I have an <a> tag instead of a <button>.

I want to disable the mat menu trigger. If I use the button tag, it works, if I use it as an ancor tag, it still opens up the menu:

enter image description here

Any ideas how to prevent this with anchor link tags? Stackblitz example here.

like image 404
ForestG Avatar asked Feb 19 '19 12:02

ForestG


People also ask

How to disable a mat menu item?

To disable the mat menu item we can use disable property.

How do you prevent angular material mat menu from closing?

stoppropagation() on each mat-menu-item to prevent it from closing.

What is matMenuTriggerFor?

matMenuTriggerFor is passed the menu identifier to attach the menus.

How to change the position of mat menu?

Changing mat menu positionThe xPosition attribute sets the menu all along the horizontal axis. The yPosition attribute is used to change the menu's vertical position. Set the yPosition property to "above" to display the menu just above the menu trigger element. The values "above" and "below" are accepted by yPosition.


2 Answers

well, the anchor tag doesn't have disabled property so you can't disable it this way.
you may change it to button and change it's style .

or you may use
pointer-events: none

to disable clicking on it.
for example :

<a mat-button [matMenuTriggerFor]="menu" [ngClass]="{ 'disabled' :condition }">Menu</a>
 <mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
 </mat-menu>

and in CSS :

.disabled {
  pointer-events:none;
  opacity:.5;
 }
like image 133
Yahya Essam Avatar answered Oct 02 '22 12:10

Yahya Essam


In my solution, I simply disabled click event handling by subclassing MatMenuTrigger.

import {Directive, Input} from '@angular/core';
import {MatMenuTrigger, MatMenuPanel} from '@angular/material/menu';

@Directive({
    selector: `[sgMenuTriggerFor]`,
    exportAs: 'sgMenuTrigger'
})
export class SgMenuTrigger extends MatMenuTrigger {
    _handleClick(event: MouseEvent): void {}

    @Input('sgMenuTriggerFor')
    get menu() { return super.menu; }
    set menu(menu: MatMenuPanel) {
        super.menu = menu;
    }
}
like image 42
Balázs Szórádi Avatar answered Oct 02 '22 12:10

Balázs Szórádi