Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Angular Material Menu can be utilized as a context menu by following these steps:

  1. Import MatMenuModule from @angular/material in the module where the context menu will be used.
  2. Create a menu template using the mat-menu directive with a #menuTrigger="matMenuTrigger" attribute on the trigger element.
  3. Set the matMenuTrigger input property to a variable that can be accessed in code.
  4. Add an event listener to the trigger element and prevent the default behavior (contextmenu is a common event to use for this).
  5. Get the position of the click event and use the 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.