Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open the context menu by PrimeNG from code Angular 2

I need to open the context menu by PrimeNG in table using button and using the right click. I found the method 'toggle' and 'show' into component for open the menu, but it's not open. When I call the method, I setting new position for menu, but a property 'display' still has a 'none', but with a new position. For getting a component 'contextMenu' from template in typescript, I use ViewChild by Angular.

like image 288
Daniel Morozov Avatar asked Apr 24 '17 14:04

Daniel Morozov


2 Answers

Add a context menu and a click event on a button/span/div/etc that references the local variable (cm in this example) and calls the show or toggle function.

<p-contextMenu #cm [model]="items"></p-contextMenu>

<button (click)="cm.show($event);$event.stopPropagation();">Show context</button>

Feel free to pass this to a function which will handle it:

(click)="showContext(cm, $event)"

In the TS:

showContext(cm: ContextMenu, event :MouseEvent) {
  cm.show(event);
  event.stopPropagation();
}

The most important thing that seems to be necessary (at least on PrimeNG 7) is the event.stopPropagation(). Without it, if you view the DOM, you will see the context menu reacting to the show() event but the display stays as none.

The other important thing is passing the mouse event in the show() which lets the context menu appear where your cursor is, otherwise it appears elsewhere on the page.

If attempting to call the show/toggle purely through code and using the ViewChild without a click event happening, you can try to manually edit the style and change the display:none to a display:block (as detailed in the comment by Y. Tarion)

like image 103
JAC Avatar answered Nov 18 '22 23:11

JAC


You can open programmatically a contextMenu PrimeNG but it's a little tricky.

Your ContextMenu in your template :

<p-contextMenu #cm [global]="true" [model]="items"></p-contextMenu>

On your button : (click)="toggle($event)"

On your typescript, here an example of the toggle method :

  toggle(event){
    if(!this.cm.containerViewChild.nativeElement.style.display ||
      this.cm.containerViewChild.nativeElement.style.display == 'none') {
      //Open contextual menu
      setTimeout(() => {
        this.cm.position(event);
        this.cm.containerViewChild.nativeElement.style.display = 'block';
        this.cm.containerViewChild.nativeElement.style.visiblility = 'visible';
      }, 0);
    }else{
      //close contextual menu
      setTimeout(() => {
        this.cm.containerViewChild.nativeElement.style.display = 'none';
      }, 0);
    }
  }

Where cm is your ContextMenu

@ViewChild("cm") cm:ContextMenu;

Or, it exists an alternative from the ContextMenu for this use case : the PrimeNG's tiered menu

like image 2
Y. Tarion Avatar answered Nov 19 '22 00:11

Y. Tarion