Change menu items dynamically in Angular Context menu component

27 Apr 20244 minutes to read

The items visible in the ContextMenu can be changed dynamically based on the target in which you open the ContextMenu. To achieve this behavior, initialize ContextMenu with all items using items property and then based on the context you open hide/show required items using hideItems/ showItems method in beforeOpen event.

In the following example, the datasource for Clipboard div is Cut, Copy, Paste and for the Editor div is Add, Edit, Delete is changed on beforeOpen event using hideItems and showItems method.

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 { MenuItemModel, BeforeOpenCloseMenuEventArgs } from '@syncfusion/ej2-navigations';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';

@Component({
imports: [
        
        ContextMenuModule
    ],


standalone: true,
  selector: 'app-root',
  template: `<div class="e-section-control">
            <!--target element-->
            <div id="target">
              <div id='left' class='e-div'>Clipboard</div>
              <div id='right' class='e-div'>Editor</div>
            </div>
            <!-- To Render ContextMenu. -->
            <ejs-contextmenu #contextmenu target='#target .e-div' [items]= 'menuItems' (beforeOpen)='beforeOpen($event)'></ejs-contextmenu>
            </div>`
})

export class AppComponent {
    @ViewChild('contextmenu')
    public cmenu?: ContextMenuComponent;
    // Initialize menu items.
    public menuItems: MenuItemModel[] = [
    {
        text: 'Cut'
    },
    {
        text: 'Copy'
    },
    {
        text: 'Paste'
    },
    {
        text: 'Add'
    },
    {
        text: 'Edit'
    },
    {
        text: 'Delete'
    }];

    public beforeOpen (args: BeforeOpenCloseMenuEventArgs) {
       // To hide/show items on right click.
        if ((args.event.target as HTMLElement).id === 'right') {
                (this.cmenu as ContextMenuComponent).hideItems(['Cut', 'Copy', 'Paste']);
                (this.cmenu as ContextMenuComponent).showItems(['Add', 'Edit', 'Delete']);
        } else if ((args.event.target as HTMLElement).id === 'left') {
            (this.cmenu as ContextMenuComponent).showItems(['Cut', 'Copy', 'Paste']);
            (this.cmenu as ContextMenuComponent).hideItems(['Add','Edit','Delete']);
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));