Enable or disable context menu items in Angular Context menu component
4 Sep 20254 minutes to read
The ContextMenu component supports dynamic state management of menu items through the enableItems method. This functionality allows you to control menu item availability based on application state, user permissions, or contextual conditions, enhancing user experience by showing only relevant actions.
The enableItems method accepts three parameters: an array of item identifiers (items), a boolean value (enable) to specify the desired state, and an optional isUniqueId parameter to indicate whether the identifiers refer to unique IDs or text content. When enable is set to true, the specified items become interactive; when false, they become disabled and visually dimmed.
In the following example, the Display Settings parent item and Medium icons sub menu item are disabled to demonstrate different levels of menu item control.
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()' (beforeOpen)='beforeOpen()'></ejs-contextmenu>
</div>`
})
export class AppComponent {
@ViewChild('contextmenu')
public contextmenu?: ContextMenuComponent;
// ContextMenu items definition
public menuItems: MenuItemModel[] = [
{
text: 'View',
items: [
{
text: 'Large icons'
},
{
text: 'Medium icons'
},
{
text: 'Small icons'
}
]
},
{
text: 'Sort By'
},
{
text: 'Refresh'
},
{
separator: true
},
{
text: 'New'
},
{
separator: true
},
{
text: 'Display Settings'
},
{
text: 'Personalize'
}];
onCreated(): void {
(this.contextmenu as ContextMenuComponent).enableItems(['Display Settings'], false);
}
beforeOpen(): void {
(this.contextmenu as ContextMenuComponent).enableItems(['Medium icons'], false);
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));To disable sub menu items, use the
beforeOpenevent.