Use*_*132 14 contextmenu angular
你如何创建一个上下文菜单angular 4
?不幸的是,html上下文菜单不起作用.
所以我想创建一个组件并在光标坐标处右键单击显示它,但是如何实现呢?
例如
<ul>
<li (click)="showContextMenuComponent">example</li>
</ul
Run Code Online (Sandbox Code Playgroud)
Use*_*132 31
我发现你所有的解决方案都非常复杂,很难定制,因为我刚刚开始,我想用组件和事件绑定来解决这个问题.所以我的ContextMenu是一个输入值为x和y的组件,右键单击它的ParentComponent :)
所以这里是:
Parent.component.ts
export class parentComponent {
contextmenu = false;
contextmenuX = 0;
contextmenuY = 0;
//activates the menu with the coordinates
onrightClick(event){
this.contextmenuX=event.clientX
this.contextmenuY=event.clientY
this.contextmenu=true;
}
//disables the menu
disableContextMenu(){
this.contextmenu= false;
}
Run Code Online (Sandbox Code Playgroud)
parent.component.html
<!-- your whole html is wrapped in a div so anywhere you click you disable contextmenu,
also the div is responsible for suppressing the default browser contextmenu -->
<div (click)="disableContextMenu()" oncontextmenu="return false;">
<!-- this is the usage -->
<ul>
<li (contextmenu)="onrightClick($event)">right click me!</li>
</ul>
<!--you have to write this only once in your component-->
<div *ngIf="contextmenu">
<app-contextmenu [x]="contextmenuX" [y]="contextmenuY"></app-contextmenu>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这是上下文菜单本身:
contextmenu.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-contextmenu',
})
export class ContextmenuComponent{
constructor() { }
@Input() x=0;
@Input() y=0;
}
Run Code Online (Sandbox Code Playgroud)
contextmenu.component.html
<div class="contextmenu" [ngStyle]="{'left.px': x, 'top.px': y}">
this is your contextmenu content
</div>
Run Code Online (Sandbox Code Playgroud)
contextmenu.component.css
.contextmenu{
position: absolute;
}
Run Code Online (Sandbox Code Playgroud)
您现在可以像往常一样使用组件来应用自己的动画,CSS样式等.希望这可以帮助:)玩得开心!
解决方案:(使用 Angular 9 测试):
在 HTML 中:
<div (click)="itemClicked($event);" (contextmenu)="itemClicked($event);">
Click Me!!!
</div>
Run Code Online (Sandbox Code Playgroud)
在 TS 中:
itemClicked($event) {
console.log($event);
/* Use the following properties to differentiate between left and right click respectively.
* $event.type will be "click" or "contextmenu"
* $event.which will be "1" or "3"
*/
// To prevent browser's default contextmenu
$event.preventDefault();
$event.stopPropagation();
// To show your modal or popover or any page
this.openQuickDialog($event); // FYI, this line calls my other method to open Popover dialog.
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用角度材质菜单的现场示例。当您右键单击一个项目时,它会将菜单的位置设置为鼠标位置并打开它。
我发布了这个答案;以防万一它可能会帮助像我这样的人。