How to Angular 4 context menu
I found all your solutions quite complicated and hard to customize, and since i just started i wanted to solve this with components and eventbinding only. So My ContextMenu is a component with Input values x and y and is shown on right click on top of its ParentComponent :)
Stackblitz Example
So here it is:
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;
}
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>
This is the context menu itself:
contextmenu.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-contextmenu',
})
export class ContextmenuComponent{
constructor() { }
@Input() x=0;
@Input() y=0;
}
contextmenu.component.html
<div class="contextmenu" [ngStyle]="{'left.px': x, 'top.px': y}">
this is your contextmenu content
</div>
contextmenu.component.css
.contextmenu{
position: absolute;
}
You can now apply your own animations, css styling, etc. as usual with a component. Hope this could help :) have fun !
You can try ngx-contextmenu library. Check the demo here
If you are on angular version 4 consider using [email protected]