Angular Material 自定义上下文菜单(右键单击)

问题描述 投票:0回答:1

使用 Angular Material,是否可以在指定的模板元素上使用我自己的 MatMenu 覆盖默认上下文菜单(右键单击)?

MatMenuTrigger 指令,但它只支持左键单击触发。此外,它仅显示 MatMenu 相对于元素的固定位置,而不是触发时的鼠标位置。

我尝试过 CdkMenu,但我无法让它与 MatMenu 一起使用。

angular angular-material contextmenu
1个回答
0
投票

您可以使用以下代码打开您自己的上下文菜单

在您的 component.html 文件中,您需要放置此代码

<div (contextmenu)="onRightClick($event)"></div>

您可以将以下代码放在html文件末尾

<!-- an hidden div is created to set the position of appearance of the menu-->
<div style="visibility: hidden; position: fixed;" [style.left]="menuTopLeftPosition.x"
    [style.top]="menuTopLeftPosition.y" [matMenuTriggerFor]="rightMenu"></div>

<!-- standard material menu -->
<mat-menu #rightMenu="matMenu">
    <ng-template matMenuContent let-item="item" *transloco="let t">
        <button mat-menu-item>Option 1</button>
        <button mat-menu-item>Option 2</button>
        <button mat-menu-item>Option 3</button>
        <button mat-menu-item>Option 4</button>
    </ng-template>
</mat-menu>

在您的 component.ts 文件中

@ViewChild(MatMenuTrigger, { static: true }) matMenuTrigger: MatMenuTrigger;

onRightClick(event) {
    if (!row.isDropAccept && row.isFromServer) {
      // preventDefault avoids to show the visualization of the right-click menu of the browser 
      event.preventDefault();

      // we record the mouse position in our object 
      this.menuTopLeftPosition.x = event.clientX + 'px';
      this.menuTopLeftPosition.y = event.clientY + 'px';
      // we open the menu 
      this.matMenuTrigger.openMenu();
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.