Access the PrimeNG context menu in Angular 2 by using code to open it

I am trying to open the context menu provided by PrimeNG in a table by using a button and right click. Although I have found the methods 'toggle' and 'show' in the component, the menu is not opening. Even after setting a new position for the menu when calling the method, the 'display' property remains 'none'. In order to access the 'contextMenu' component from the template in typescript, I am utilizing ViewChild in Angular.

Answer №1

Implement a context menu along with a click event on a button, span, or div that makes use of a local variable (cm in this case) and invokes the show or toggle function.

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

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

You can also delegate this to a function for handling:

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

In the TypeScript file:

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

An important aspect to consider (especially on PrimeNG 7) is the event.stopPropagation(). Without this, the context menu may react to the show() event but not display properly.

Another key point is passing the mouse event in the show() function to ensure the context menu appears at the cursor position instead of elsewhere on the page.

If you need to trigger the show/toggle function programmatically without a click event using ViewChild, you may opt to manually modify the style by changing display:none to display:block (as suggested by Y. Tarion in a comment).

Answer №2

If you want to programmatically open a contextMenu in PrimeNG, there is a slightly tricky way to do it.

First, you need to define your ContextMenu in your template:

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

Next, add the following code to your button: (click)="toggle($event)"

Then, in your typescript file, you can use the following example for 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);
    }
  }

Remember to define cm as your ContextMenu in your typescript file:

@ViewChild("cm") cm:ContextMenu;

Alternatively, you can also consider using the PrimeNG's tiered menu for this purpose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create metadata.json and ngsummary.json files in Angular 2

Hello fellow Angular 2 developers, I've been running into some trouble trying to find comprehensive documentation on the angular 2 compiler (ngc). Here's my situation: I have a directory that contains an Angular 2 logging library with a main fi ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

What is the best way to center vertically the angular + material mat-checkbox outside of a form group?

I am faced with two scenarios: The first scenario involves using a FORM GROUP with Angular 5 and Angular Material Design. Below is the code for handling multiple checkboxes: <div *ngSwitchCase="'checkboxField'" class="checkbox-field"> ...

"Error: The method setValue is not found in the AbstractControl type" when trying to clear form in Angular 2

Here is the template code: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate"> <textarea [ngClass]="{ 'error': comment }" [formControl]="form.controls['comment']" ...

Exploring the incorporation of an inclusive switch statement within a Redux reducer utilizing Typescript. Strategies for managing Redux's internal @@redux actions

After conducting extensive research, I have yet to discover a definitive answer to this query. There is a question posted on Stack Overflow that provides guidance on how to implement a thorough switch statement: How can I ensure my switch block covers al ...

When using Typescript, you may encounter the error message "Declaration file for module 'xmlhttprequest' not found."

When trying to use the following code on Node: import { XMLHttpRequest } from 'xmlhttprequest'; I encountered the following error while compiling with tsc: index.ts|4 col 32 error| 7016[QF available]: Could not find a declaration file for mo ...

Angular module with customizable configurations

I am interested in developing a customizable Angular 9 module with IVY and AOT enabled. In the latest version of Angular, IVY and AOT are automatically activated: npx @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8 ...

What is the best way to prevent updating the state before the selection of the end date in a date range using react-datepicker?

Managing user input values in my application to render a chart has been a bit tricky. Users select a start date, an end date, and another parameter to generate the chart. The issue arises when users need to edit the dates using react-datepicker. When the s ...

Sorry, but the content and map of this Angular 12 source are currently unavailable. Please note that only the `size()` method

Following an update to the most recent version of Angular, I encountered the following error message: The content and map of this source are not accessible (only size() is supported) I would greatly appreciate any assistance with this issue, as there is l ...

Transport parameter via routerLink to a different component

When I click on the link provided in the list-profile HTML document, I need to send a variable. However, the current code is not working and causing crashes. If more details are required, feel free to ask. List Profile Component HTML <div class="col c ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...

What is the reason for the request producing additional data beyond what was input into the interface?

When making a request for an API that contains multiple values, it can be frustrating when unwanted values are included in the response. To address this issue, interfaces are created to accurately define and use the necessary objects. However, the object ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Encountering an issue with importing an enum: An error is triggered stating 'Variable implicitly has type 'any' in certain areas where its type remains undetermined.'

When I define simple enums in the same file, everything works fine. However, exporting/importing them causes numerous compilation errors related to types. It seems like the issue only arises when defining enums in a separate file, pointing towards a proble ...

This code cannot be called as a function, Every individual in the union

My approach has been aligned with the current architecture, focusing on reducing complexity as much as possible. I have strived for the best possible outcome, but encountered a single failed test along the way. After three days of struggling, I'm cl ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

What is the method for defining specific requirements for a generic type's implementation?

I am facing an issue with the following code snippet, where I am trying to restrict the pairing of Chart objects based on correct types for the data and options objects. However, despite my efforts, the TypeScript compiler is not throwing an error in the s ...

Troubleshoot: Angular hide/show feature malfunctioning

I am facing an issue where clicking on one parent element causes all parent elements to show or hide their child elements accordingly. I am relatively new to Angular 2 and would appreciate any recommendations. Below, you can see the code for the component ...