Open and close contextmenu in Angular Context menu component

4 Sep 20253 minutes to read

The ContextMenu component can be opened and closed programmatically using the open and close methods. This programmatic control is useful for creating custom trigger events or implementing context menu functionality in response to specific user interactions.

The open method accepts three parameters:

  • top: To specify ContextMenu vertical positioning.
  • left: To specify ContextMenu horizontal positioning.
  • target: To calculate z-index for ContextMenu based upon the specified target.

In the following example, the ContextMenu is opened using the open method at the specified position using top and left coordinates. The ContextMenu is closed using the close method on ContextMenu item click or document click.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { ContextMenuModule } from '@syncfusion/ej2-angular-navigations'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { enableRipple } from '@syncfusion/ej2-base'



import { Component } from '@angular/core';
import { getInstance } from '@syncfusion/ej2-base';
import { MenuItemModel, ContextMenu } from '@syncfusion/ej2-navigations';

@Component({
imports: [
        
        ContextMenuModule,
        ButtonModule
    ],


standalone: true,
  selector: 'app-root',
  template: `<div class="e-section-control">
            <!-- To Render ContextMenu. -->
            <ejs-contextmenu id='contextmenu' [items]= 'menuItems'></ejs-contextmenu>
            <!-- To Render Button. -->
            <button ejs-button (click)="btnClick()">Open ContextMenu</button>
            </div>`
})

export class AppComponent  {
    // Initialize action items.
    public menuItems: MenuItemModel[] = [
        {
            text: 'Cut'
        },
        {
            text: 'Copy'
        },
        {
            text: 'Paste'
        }];

    btnClick() {
        let contextmenuObj: ContextMenu = getInstance(document.getElementById("contextmenu_0") as HTMLElement, ContextMenu) as ContextMenu;
        contextmenuObj.open(40, 20);
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));