Using Angular Material matMenu as context menu

Discussão em 'Angular' iniciado por GGizmos, Maio 28, 2025.

  1. GGizmos

    GGizmos Guest

    I have been trying to sort out how to use a matMenu as context menu triggered when somebody right clicks on one of my elements.

    This is my menu:

    <mat-menu #contextMenu="matMenu">
    <button mat-menu-item>
    <mat-icon>table_rows</mat-icon>
    <span>Select Whole Row</span>
    <span>⌘→</span>
    </button>
    <button mat-menu-item>
    <mat-icon>functions</mat-icon>
    <span>Insert Subtotal</span>
    <span>⌃S</span>
    </button>
    </mat-menu>


    I want to be able to trigger the menu when this element is right-clicked:

    <div tabindex=0 *ngIf="!hasRowFocus"
    class="display-cell" (keydown)="onSelectKeyDown($event)"
    (click)=selectCellClick($event)
    (dblclick)=selectCellDblClick($event)
    (contextmenu)="openContextMenu()"
    [ngClass]='selectClass'
    (mouseover)="mouseover()"
    (mouseout)="mouseout()"

    #cellSelect >
    <div (dragenter) = "mouseDragEnter($event)" (dragleave) = "mouseDragLeave($event)">{{templateDisplayValue}}</div>
    </div>


    However, according to the documentation, I need to specify this div should have the [matMenuTriggerFor] directive, so that so when openContextMenu() it triggered by right clicking, I can call get a reference to the trigger element and then call triggerElement.trigger() to spawn the menu.

    Problem is it appears that setting [matMenuTriggerFor] is hooked up to the click event automatically, not the right click event, so anytime I left click on the element the context menu opens, which is not the desired behavor.

    I have seen workarounds like this one on Stackblitz which creates a hidden div as the trigger element, but requires supplying x & y coordinates for the location of the menu element which seems suboptimal.

    Any way to have the menu triggered by right clicking on the input element without having to create a dummy element to host the matMenuTriggerFor directive?

    Continue reading...

Compartilhe esta Página