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:
Any ideas how to prevent this with anchor
link tags?
Stackblitz example here.
To disable the mat menu item we can use disable property.
stoppropagation() on each mat-menu-item to prevent it from closing.
matMenuTriggerFor is passed the menu identifier to attach the menus.
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.
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;
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With