【发布时间】:2021-02-03 18:41:06
【问题描述】:
我一直在试图弄清楚如何使用 matMenu 作为上下文菜单,当有人右键单击我的一个元素时触发。
这是我的菜单:
<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>
我希望能够在右键单击此元素时触发菜单:
<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>
但是,根据文档,我需要指定这个div应该有[matMenuTriggerFor]指令,这样当openContextMenu()被右键点击触发时,我可以调用获取对触发元素的引用,然后调用triggerElement.trigger() 生成菜单。
问题是设置[matMenuTriggerFor] 似乎自动连接到点击事件,而不是右键点击事件,所以每当我左单击元素时,上下文菜单会打开,这不是期望的行为。
我在Stackblitz 上看到过类似的解决方法,它创建一个隐藏的 div 作为触发元素,但需要为菜单元素的位置提供 x 和 y 坐标,这似乎不是最佳的。
有什么方法可以通过右键单击输入元素来触发菜单,而不必创建一个虚拟元素来承载 matMenuTriggerFor 指令?
【问题讨论】:
-
扩展 MatMenuTrigger 并覆盖装饰器?