Angular Material Menu can be utilized as a context menu by following these steps:
MatMenuModule
from @angular/material
in the module where the context menu will be used.mat-menu
directive with a #menuTrigger="matMenuTrigger"
attribute on the trigger element.matMenuTrigger
input property to a variable that can be accessed in code.contextmenu
is a common event to use for this).openMenu()
method on the menu trigger to open the context menu at that position.Example code:
HTML template:
<button mat-icon-button [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger" (contextmenu)="onContextMenu($event)">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>Option 1</button>
<button mat-menu-item>Option 2</button>
</mat-menu>
Component code:
import { Component, ViewChild } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
@Component({
selector: 'app-context-menu',
templateUrl: './context-menu.component.html',
styleUrls: ['./context-menu.component.css']
})
export class ContextMenuComponent {
@ViewChild('menuTrigger') menuTrigger: MatMenuTrigger;
onContextMenu(event: MouseEvent) {
event.preventDefault();
this.menuTrigger.menuData = { event };
this.menuTrigger.openMenu();
}
}
In this example, the context menu is opened when the button
element is right-clicked (contextmenu
event). The onContextMenu()
method prevents the default event behavior and sets the mouse position in the menuData
property of the MatMenuTrigger
object before opening the context menu.
Asked: 2021-09-08 11:00:00 +0000
Seen: 1 times
Last updated: Feb 22 '22