Search results

Change menu items dynamically in Angular ContextMenu component

14 Apr 2021 / 2 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.

Source
Preview
app.component.ts
app.module.ts
main.ts
Copied to clipboard
import { Component, ViewChild } from '@angular/core';
import { MenuItemModel, BeforeOpenCloseMenuEventArgs } from '@syncfusion/ej2-navigations';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';

@Component({
  selector: 'app-root',
  template: `<!--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>`
})

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.hideItems(['Cut', 'Copy', 'Paste']);
          this.cmenu.showItems(['Add', 'Edit', 'Delete']);
       } else if ((args.event.target as HTMLElement).id === 'left') {
          this.cmenu.showItems(['Cut', 'Copy', 'Paste']);
          this.cmenu.hideItems(['Add','Edit','Delete']);
       }
    }
}
Copied to clipboard
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ContextMenuModule } from '@syncfusion/ej2-angular-navigations';
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        ContextMenuModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
Copied to clipboard
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);