Add or remove context menu items in Angular Context menu component

4 Sep 20254 minutes to read

The ContextMenu component provides dynamic item management capabilities, allowing you to add or remove menu items programmatically at runtime. This functionality enables responsive menu systems that adapt to changing application states, user permissions, or contextual requirements.

ContextMenu items can be dynamically modified using the insertAfter, insertBefore and removeItems methods.

The insertAfter method adds new menu items after a specified target item, while insertBefore adds items before the target. The removeItems method removes specified items from the menu structure.

In the following example, the Display Settings menu items are added before the Personalize item, the Sort By menu items are added after the Refresh, and the Paste item is removed from context menu.

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



import { Component, ViewChild } from '@angular/core';
import { ContextMenuComponent, MenuEventArgs, MenuItemModel } from '@syncfusion/ej2-angular-navigations';

@Component({
imports: [
        
        ContextMenuModule
    ],


standalone: true,
  selector: 'app-root',
  template: `<div class="e-section-control">
            <!--target element-->
            <div id="target">Right click / Touch hold to open the ContextMenu</div>
            <!-- To Render ContextMenu. -->
            <ejs-contextmenu #contextmenu target='#target' [items]='menuItems' (created)='onCreated()'></ejs-contextmenu>
            </div>`
})

export class AppComponent {
     @ViewChild('contextmenu')
    public contextmenu?: ContextMenuComponent;

    public menuItems: MenuItemModel[] = [
    {
        text: 'View',
        items: [
          {
            text: 'Large icons'
          },
          {
            text: 'Medium icons'
          },
          {
            text: 'Small icons'
          }
        ]
    },
    {
        text: 'Refresh'
    },
    {
        text: 'Paste'
    },
    {
        separator: true
    },
    {
        text: 'New'
    },
    {
        separator: true
    },
    {
        text: 'Personalize'
    }];

    onCreated(): void {
      (this.contextmenu as ContextMenuComponent).insertAfter([{text: 'Sort By'}] , 'Refresh');
      (this.contextmenu as ContextMenuComponent).insertBefore([{text: 'Display Settings'}] , 'Personalize');
      (this.contextmenu as ContextMenuComponent).removeItems(['Paste']);
    }

}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));