syncfusion-angular-context-menu

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing Syncfusion Angular ContextMenu

实现Syncfusion Angular ContextMenu

The ContextMenu is a graphical user interface that appears when users right-click or perform touch-hold actions. It provides a context-aware menu with support for nested items, dynamic updates, animations, custom templates, and comprehensive event handling. This skill guides you through implementing, configuring, and customizing context menus for Angular applications.
ContextMenu是一种图形用户界面,当用户右键点击或执行长按操作时会显示。它提供了支持嵌套项、动态更新、动画、自定义模板和全面事件处理的上下文感知菜单。本技能将指导你在Angular应用中实现、配置和自定义上下文菜单。

When to Use This Skill

何时使用此技能

Use this skill when:
  • You need to create a right-click or touch-hold context menu
  • Managing menu items dynamically (add, remove, enable, disable)
  • Handling menu item click events and actions
  • Opening dialogs or navigating from menu selections
  • Customizing menu appearance with animations, icons, or themes
  • Showing/hiding items based on context or user permissions
  • Binding menu items from data sources
  • Creating complex menu templates or nested structures
  • Implementing responsive menus with scrolling
  • Adding keyboard shortcuts or accessibility features
在以下场景使用此技能:
  • 你需要创建右键点击或长按触发的上下文菜单
  • 动态管理菜单项(添加、移除、启用、禁用)
  • 处理菜单项点击事件和对应操作
  • 通过菜单选择打开对话框或进行页面导航
  • 使用动画、图标或主题自定义菜单外观
  • 根据上下文或用户权限显示/隐藏菜单项
  • 从数据源绑定菜单项
  • 创建复杂的菜单模板或嵌套结构
  • 实现带滚动功能的响应式菜单
  • 添加键盘快捷键或无障碍功能

Component Overview

组件概述

The ContextMenu component enables intuitive right-click interfaces with:
  • ✅ Dynamic item management (add/remove/enable/disable)
  • ✅ Multi-level nested menus
  • ✅ Data binding from arrays or objects
  • ✅ Customizable animations (FadeIn, SlideDown, ZoomIn, None)
  • ✅ Template support for rich content (icons, HTML, tables)
  • ✅ Event handling (click, open, close)
  • ✅ Icon and URL navigation
  • ✅ Scrollable menus for large item lists
  • ✅ Accessibility with keyboard support
ContextMenu组件为右键交互界面提供以下功能:
  • ✅ 动态项管理(添加/移除/启用/禁用)
  • ✅ 多级嵌套菜单
  • ✅ 从数组或对象进行数据绑定
  • ✅ 可自定义动画(FadeIn、SlideDown、ZoomIn、None)
  • ✅ 支持富内容模板(图标、HTML、表格)
  • ✅ 事件处理(点击、打开、关闭)
  • ✅ 图标和URL导航
  • ✅ 支持大列表的可滚动菜单
  • ✅ 带键盘支持的无障碍功能

Documentation and Navigation Guide

文档与导航指南

Getting Started

快速入门

📄 Read: references/getting-started.md
  • Package installation and dependencies
  • Angular environment setup (standalone architecture)
  • Creating your first ContextMenu
  • Configuring target elements
  • Basic menu item structure
📄 阅读: references/getting-started.md
  • 包安装和依赖项
  • Angular环境设置(独立架构)
  • 创建你的第一个ContextMenu
  • 配置目标元素
  • 基础菜单项结构

Menu Items Management

菜单项管理

📄 Read: references/menu-items-management.md
  • Adding menu items dynamically (insertBefore, insertAfter)
  • Removing menu items (removeItems method)
  • Enabling and disabling items (enableItems)
  • Showing and hiding items (showItems, hideItems)
  • Dynamic context-aware menus
  • Multi-level nested menus
📄 阅读: references/menu-items-management.md
  • 动态添加菜单项(insertBefore、insertAfter)
  • 移除菜单项(removeItems方法)
  • 启用和禁用菜单项(enableItems)
  • 显示和隐藏菜单项(showItems、hideItems)
  • 动态上下文感知菜单
  • 多级嵌套菜单

Data Binding

数据绑定

📄 Read: references/data-binding.md
  • Populating items from data sources
  • MenuItemModel structure and properties
  • Parent-child item relationships
  • beforeItemRender event for item formatting
  • Dynamic data updates
📄 阅读: references/data-binding.md
  • 从数据源填充菜单项
  • MenuItemModel结构和属性
  • 父子项关系
  • 用于项格式化的beforeItemRender事件
  • 动态数据更新

Interaction & Events

交互与事件

📄 Read: references/interaction-and-events.md
  • Menu item click handlers (select event)
  • Click-to-open submenus (showItemOnClick)
  • Programmatic open and close methods
  • Menu positioning with coordinates
  • Opening dialogs on item selection
  • MenuEventArgs and event properties
📄 阅读: references/interaction-and-events.md
  • 菜单项点击处理器(select事件)
  • 点击打开子菜单(showItemOnClick)
  • 程序化打开和关闭方法
  • 基于坐标的菜单定位
  • 选择项时打开对话框
  • MenuEventArgs和事件属性

Styling & Customization

样式与自定义

📄 Read: references/styling-and-customization.md
  • Animation settings and effects (FadeIn, SlideDown, ZoomIn, None)
  • CSS customization and class targeting
  • Icon styling with iconCss property
  • URL navigation and external links
  • Scrollable menus (enableScrolling)
  • Responsive design and Theme Studio
📄 阅读: references/styling-and-customization.md
  • 动画设置和效果(FadeIn、SlideDown、ZoomIn、None)
  • CSS自定义和类目标定位
  • 使用iconCss属性设置图标样式
  • URL导航和外部链接
  • 可滚动菜单(enableScrolling)
  • 响应式设计和Theme Studio

Templates & Advanced Features

模板与高级功能

📄 Read: references/templates-and-advanced.md
  • Custom item templates (itemTemplate)
  • Rich content with HTML and tables
  • Character underlining and formatting
  • Separator items and grouping
  • Accessibility and keyboard navigation
  • Advanced template patterns
📄 阅读: references/templates-and-advanced.md
  • 自定义项模板(itemTemplate)
  • 包含HTML和表格的富内容
  • 字符下划线和格式化
  • 分隔符项和分组
  • 无障碍和键盘导航
  • 高级模板模式

Quick Start Example

快速入门示例

typescript
import { Component } from '@angular/core';
import { ContextMenuModule } from '@syncfusion/ej2-angular-navigations';
import { MenuItemModel } from '@syncfusion/ej2-navigations';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div class="e-section-control">
      <!-- Target element for context menu -->
      <div id="target">Right click / Touch hold to open the ContextMenu</div>
      
      <!-- ContextMenu component -->
      <ejs-contextmenu 
        id='contextmenu' 
        target='#target' 
        [items]='menuItems'>
      </ejs-contextmenu>
    </div>
  `
})
export class AppComponent {
  public menuItems: MenuItemModel[] = [
    { text: 'Cut', iconCss: 'e-cm-icons e-cut' },
    { text: 'Copy', iconCss: 'e-cm-icons e-copy' },
    { text: 'Paste', iconCss: 'e-cm-icons e-paste' },
    { separator: true },
    {
      text: 'View',
      items: [
        { text: 'Large icons' },
        { text: 'Small icons' }
      ]
    }
  ];
}
typescript
import { Component } from '@angular/core';
import { ContextMenuModule } from '@syncfusion/ej2-angular-navigations';
import { MenuItemModel } from '@syncfusion/ej2-navigations';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div class="e-section-control">
      <!-- Context菜单的目标元素 -->
      <div id="target">右键点击 / 长按打开ContextMenu</div>
      
      <!-- ContextMenu组件 -->
      <ejs-contextmenu 
        id='contextmenu' 
        target='#target' 
        [items]='menuItems'>
      </ejs-contextmenu>
    </div>
  `
})
export class AppComponent {
  public menuItems: MenuItemModel[] = [
    { text: '剪切', iconCss: 'e-cm-icons e-cut' },
    { text: '复制', iconCss: 'e-cm-icons e-copy' },
    { text: '粘贴', iconCss: 'e-cm-icons e-paste' },
    { separator: true },
    {
      text: '视图',
      items: [
        { text: '大图标' },
        { text: '小图标' }
      ]
    }
  ];
}

Common Patterns

常见模式

Pattern 1: Dynamic Item Management

模式1:动态项管理

typescript
// Add items after 'Refresh'
this.contextmenu.insertAfter([{ text: 'Sort By' }], 'Refresh');

// Remove 'Paste' item
this.contextmenu.removeItems(['Paste']);

// Disable 'Edit' item
this.contextmenu.enableItems(['Edit'], false);
typescript
// 在“刷新”后添加项
this.contextmenu.insertAfter([{ text: '排序方式' }], 'Refresh');

// 移除“粘贴”项
this.contextmenu.removeItems(['Paste']);

// 禁用“编辑”项
this.contextmenu.enableItems(['Edit'], false);

Pattern 2: Context-Aware Menus

模式2:上下文感知菜单

typescript
beforeOpen(args: BeforeOpenCloseMenuEventArgs) {
  if ((args.event.target as HTMLElement).id === 'editor') {
    this.contextmenu.showItems(['Add', 'Edit', 'Delete']);
    this.contextmenu.hideItems(['Cut', 'Copy', 'Paste']);
  }
}
typescript
beforeOpen(args: BeforeOpenCloseMenuEventArgs) {
  if ((args.event.target as HTMLElement).id === 'editor') {
    this.contextmenu.showItems(['添加', '编辑', '删除']);
    this.contextmenu.hideItems(['剪切', '复制', '粘贴']);
  }
}

Pattern 3: Menu Item Click Handler

模式3:菜单项点击处理器

typescript
itemSelect(args: MenuEventArgs): void {
  if (args.item.text === 'Save As...') {
    this.dialogComponent.show();
  }
}
typescript
itemSelect(args: MenuEventArgs): void {
  if (args.item.text === '另存为...') {
    this.dialogComponent.show();
  }
}

Pattern 4: Animation Configuration

模式4:动画配置

typescript
public animationSettings = {
  effect: 'FadeIn',
  duration: 400,
  easing: 'ease'
};
typescript
public animationSettings = {
  effect: 'FadeIn',
  duration: 400,
  easing: 'ease'
};

Complete API Reference

完整API参考

Component Properties

组件属性

Core Configuration Properties

核心配置属性

PropertyTypeDefaultDescription
target
string
''
Required. Specifies target element selector in which the ContextMenu should be opened.
items
MenuItemModel[]
[]
Specifies menu items with its properties which will be rendered as ContextMenu.
showItemOnClick
boolean
false
Specifies whether to show the sub menu or not on click. When
true
, the sub menu will open only on mouse click.
filter
string
''
Specifies the filter selector for elements inside the target in that the context menu will be opened.
hoverDelay
number
0
If
hoverDelay
is set by particular number, the menu will open after that period (in milliseconds).
属性类型默认值描述
target
string
''
必填项。 指定ContextMenu应在其中打开的目标元素选择器。
items
MenuItemModel[]
[]
指定将被渲染为ContextMenu的菜单项及其属性。
showItemOnClick
boolean
false
指定是否在点击时显示子菜单。设为
true
时,子菜单仅在鼠标点击时打开。
filter
string
''
指定目标内元素的过滤器选择器,ContextMenu将在这些元素上打开。
hoverDelay
number
0
如果设置了特定数值的
hoverDelay
,菜单将在该时间段(毫秒)后打开。

Styling & Appearance Properties

样式与外观属性

PropertyTypeDefaultDescription
animationSettings
MenuAnimationSettingsModel
{ duration: 400, easing: 'ease', effect: 'SlideDown' }
Specifies the animation settings for the sub menu open/close. See Animation Settings section.
cssClass
string
''
Defines class/multiple classes separated by a space in the Menu wrapper. Use for custom styling.
enableRtl
boolean
false
Enable or disable rendering component in right to left direction.
属性类型默认值描述
animationSettings
MenuAnimationSettingsModel
{ duration: 400, easing: 'ease', effect: 'SlideDown' }
指定子菜单打开/关闭的动画设置。请查看动画设置部分。
cssClass
string
''
在菜单包装器中定义单个或多个以空格分隔的类,用于自定义样式。
enableRtl
boolean
false
启用或禁用组件从右到左方向渲染。

Data & Behavior Properties

数据与行为属性

PropertyTypeDefaultDescription
itemTemplate
string | Function
null
This property allows you to define custom templates for items in the ContextMenu. Can be string selector or template function.
locale
string
''
Overrides the global culture and localization value for this component. Default global culture is
'en-US'
.
enableScrolling
boolean
false
Specifies whether to enable/disable the scrollable option in ContextMenu.
属性类型默认值描述
itemTemplate
string | Function
null
此属性允许你为ContextMenu中的项定义自定义模板,可以是字符串选择器或模板函数。
locale
string
''
覆盖此组件的全局文化和本地化值。默认全局文化为
'en-US'
enableScrolling
boolean
false
指定是否启用ContextMenu的滚动选项。

Security & Persistence Properties

安全与持久化属性

PropertyTypeDefaultDescription
enableHtmlSanitizer
boolean
true
Specifies whether to enable the rendering of untrusted HTML values. If
true
, the component will sanitize any suspected untrusted strings and scripts before rendering them. Set to
false
only when you trust the HTML source completely.
enablePersistence
boolean
false
Enable or disable persisting component's state between page reloads. When enabled, menu state is saved in localStorage.
属性类型默认值描述
enableHtmlSanitizer
boolean
true
指定是否启用不可信HTML值的渲染。如果设为
true
,组件将在渲染前清理任何疑似不可信的字符串和脚本。仅当完全信任HTML源时才设为
false
enablePersistence
boolean
false
启用或禁用页面重载之间组件状态的持久化。启用后,菜单状态将保存到localStorage中。

Property Example - Basic Configuration

属性示例 - 基础配置

Brief Example:
typescript
@Component({
  selector: 'app-context-menu',
  template: `
    <div id="target">Right click here</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      [animationSettings]='animSettings'
      cssClass='custom-menu'>
    </ejs-contextmenu>
  `
})
export class ContextMenuComponent {
  items: MenuItemModel[] = [
    { text: 'Edit' },
    { text: 'Delete' }
  ];
  
  animSettings = {
    duration: 300,
    effect: 'FadeIn',
    easing: 'ease-out'
  };
}
Full Working Example:
typescript
import { Component, ViewChild } from '@angular/core';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';
import { MenuItemModel } from '@syncfusion/ej2-navigations';

@Component({
  selector: 'app-context-menu-config',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div class="container">
      <h3>Advanced Configuration Example</h3>
      
      <!-- Target element for context menu -->
      <div id="configTarget" class="target-box">
        Right click or touch hold to open menu
      </div>
      
      <!-- ContextMenu with complete configuration -->
      <ejs-contextmenu 
        #contextMenu
        id='contextMenu'
        target='#configTarget'
        [items]='menuItems'
        [animationSettings]='animationSettings'
        cssClass='modern-menu'
        [showItemOnClick]='true'
        [enableScrolling]='true'
        [hoverDelay]='300'
        [enableHtmlSanitizer]='true'
        [enablePersistence]='true'
        locale='en-US'>
      </ejs-contextmenu>
    </div>
  `,
  styles: [`
    .target-box {
      width: 300px;
      height: 200px;
      border: 2px dashed #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      cursor: context-menu;
    }
  `]
})
export class AdvancedContextMenuComponent {
  @ViewChild('contextMenu') contextMenu!: ContextMenuComponent;
  
  menuItems: MenuItemModel[] = [
    { text: 'Edit', iconCss: 'e-cm-icons e-edit', id: 'edit' },
    { text: 'Delete', iconCss: 'e-cm-icons e-delete', id: 'delete' },
    { separator: true },
    { text: 'More', id: 'more' }
  ];
  
  animationSettings = {
    effect: 'FadeIn' as any,
    duration: 400,
    easing: 'ease-in-out'
  };
}
简要示例:
typescript
@Component({
  selector: 'app-context-menu',
  template: `
    <div id="target">右键点击此处</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      [animationSettings]='animSettings'
      cssClass='custom-menu'>
    </ejs-contextmenu>
  `
})
export class ContextMenuComponent {
  items: MenuItemModel[] = [
    { text: '编辑' },
    { text: '删除' }
  ];
  
  animSettings = {
    duration: 300,
    effect: 'FadeIn',
    easing: 'ease-out'
  };
}
完整运行示例:
typescript
import { Component, ViewChild } from '@angular/core';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';
import { MenuItemModel } from '@syncfusion/ej2-navigations';

@Component({
  selector: 'app-context-menu-config',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div class="container">
      <h3>高级配置示例</h3>
      
      <!-- Context菜单的目标元素 -->
      <div id="configTarget" class="target-box">
        右键点击或长按打开菜单
      </div>
      
      <!-- 完整配置的ContextMenu -->
      <ejs-contextmenu 
        #contextMenu
        id='contextMenu'
        target='#configTarget'
        [items]='menuItems'
        [animationSettings]='animationSettings'
        cssClass='modern-menu'
        [showItemOnClick]='true'
        [enableScrolling]='true'
        [hoverDelay]='300'
        [enableHtmlSanitizer]='true'
        [enablePersistence]='true'
        locale='en-US'>
      </ejs-contextmenu>
    </div>
  `,
  styles: [`
    .target-box {
      width: 300px;
      height: 200px;
      border: 2px dashed #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      cursor: context-menu;
    }
  `]
})
export class AdvancedContextMenuComponent {
  @ViewChild('contextMenu') contextMenu!: ContextMenuComponent;
  
  menuItems: MenuItemModel[] = [
    { text: '编辑', iconCss: 'e-cm-icons e-edit', id: 'edit' },
    { text: '删除', iconCss: 'e-cm-icons e-delete', id: 'delete' },
    { separator: true },
    { text: '更多', id: 'more' }
  ];
  
  animationSettings = {
    effect: 'FadeIn' as any,
    duration: 400,
    easing: 'ease-in-out'
  };
}

Menu Item Properties (MenuItemModel)

菜单项属性(MenuItemModel)

MenuItemModel defines the structure for each menu item. Each item in the
items
array follows this model:
PropertyTypeOptionalDescription
text
string
NoRequired. Specifies text for menu item. This is the display label shown to users.
id
string
YesSpecifies the id for menu item. Use this for identifying items in methods like
enableItems()
,
removeItems()
, etc.
items
MenuItemModel[]
YesSpecifies the sub menu items that is the array of MenuItem model. Creates nested/hierarchical menus.
separator
boolean
YesSpecifies separator between the menu items. Separators are either horizontal or vertical lines used to group menu items. Set to
true
to create a visual divider.
iconCss
string
YesDefines class/multiple classes separated by a space for the menu Item that is used to include an icon. Menu Item can include font icon and sprite image. Example:
iconCss: 'e-icons e-edit'
.
url
string
YesSpecifies url for menu item that creates the anchor link to navigate to the url provided. When clicked, navigates to this URL.
htmlAttributes
Record<string, any>
YesSpecifies the htmlAttributes property to support adding custom attributes to the menu items. Example:
{ 'data-info': 'value', 'title': 'My Tooltip' }
.
MenuItemModel定义了每个菜单项的结构。
items
数组中的每个项都遵循此模型:
属性类型可选描述
text
string
必填项。 指定菜单项的文本,即显示给用户的标签。
id
string
指定菜单项的ID,用于在
enableItems()
removeItems()
等方法中标识项。
items
MenuItemModel[]
指定子菜单项,即MenuItem模型的数组,用于创建嵌套/层级菜单。
separator
boolean
指定菜单项之间的分隔符,分隔符是用于分组菜单项的水平线或垂直线,设为
true
可创建视觉分隔线。
iconCss
string
为菜单项定义单个或多个以空格分隔的类,用于添加图标。菜单项可包含字体图标和精灵图,示例:
iconCss: 'e-icons e-edit'
url
string
指定菜单项的URL,创建锚点链接以导航到提供的URL,点击时将导航到此URL。
htmlAttributes
Record<string, any>
指定htmlAttributes属性,支持为菜单项添加自定义属性,示例:
{ 'data-info': 'value', 'title': '我的提示' }

MenuItem Example - Basic Usage

MenuItem示例 - 基础用法

Brief Example:
typescript
items: MenuItemModel[] = [
  { text: 'Cut', id: 'cut', iconCss: 'e-icons e-cut' },
  { text: 'Copy', id: 'copy', iconCss: 'e-icons e-copy' },
  { text: 'Paste', id: 'paste', iconCss: 'e-icons e-paste' },
  { separator: true },
  { text: 'Delete', id: 'delete', iconCss: 'e-icons e-delete' }
];
Full Working Example - Complex MenuItemModel:
typescript
@Component({
  selector: 'app-menu-items-config',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div id="target">Right click for advanced menu</div>
    <ejs-contextmenu target='#target' [items]='menuItems'></ejs-contextmenu>
  `
})
export class MenuItemsComponent {
  menuItems: MenuItemModel[] = [
    // Item with icon
    {
      text: 'Edit',
      id: 'edit-item',
      iconCss: 'e-icons e-edit',
      htmlAttributes: {
        'data-action': 'edit',
        'title': 'Edit selected item'
      }
    },
    // Item with submenu
    {
      text: 'Format',
      id: 'format',
      iconCss: 'e-icons e-palette',
      items: [
        { text: 'Bold', id: 'bold' },
        { text: 'Italic', id: 'italic' },
        { text: 'Underline', id: 'underline' }
      ]
    },
    // Navigation item with URL
    {
      text: 'Visit Website',
      id: 'website',
      iconCss: 'e-icons e-export',
      url: 'https://example.com',
      htmlAttributes: { 'target': '_blank' }
    },
    // Separator
    { separator: true },
    // Item with nested submenu
    {
      text: 'Advanced',
      id: 'advanced',
      items: [
        {
          text: 'Settings',
          id: 'settings',
          items: [
            { text: 'General', id: 'general' },
            { text: 'Advanced', id: 'adv' }
          ]
        },
        { text: 'Help', id: 'help', url: 'https://help.example.com' }
      ]
    }
  ];
}
简要示例:
typescript
items: MenuItemModel[] = [
  { text: '剪切', id: 'cut', iconCss: 'e-icons e-cut' },
  { text: '复制', id: 'copy', iconCss: 'e-icons e-copy' },
  { text: '粘贴', id: 'paste', iconCss: 'e-icons e-paste' },
  { separator: true },
  { text: '删除', id: 'delete', iconCss: 'e-icons e-delete' }
];
完整运行示例 - 复杂MenuItemModel:
typescript
@Component({
  selector: 'app-menu-items-config',
  standalone: true,
  imports: [ContextMenuModule],
  template: `
    <div id="target">右键点击打开高级菜单</div>
    <ejs-contextmenu target='#target' [items]='menuItems'></ejs-contextmenu>
  `
})
export class MenuItemsComponent {
  menuItems: MenuItemModel[] = [
    // 带图标的项
    {
      text: '编辑',
      id: 'edit-item',
      iconCss: 'e-icons e-edit',
      htmlAttributes: {
        'data-action': 'edit',
        'title': '编辑选中项'
      }
    },
    // 带子菜单的项
    {
      text: '格式',
      id: 'format',
      iconCss: 'e-icons e-palette',
      items: [
        { text: '加粗', id: 'bold' },
        { text: '斜体', id: 'italic' },
        { text: '下划线', id: 'underline' }
      ]
    },
    // 带URL的导航项
    {
      text: '访问网站',
      id: 'website',
      iconCss: 'e-icons e-export',
      url: 'https://example.com',
      htmlAttributes: { 'target': '_blank' }
    },
    // 分隔符
    { separator: true },
    // 带嵌套子菜单的项
    {
      text: '高级',
      id: 'advanced',
      items: [
        {
          text: '设置',
          id: 'settings',
          items: [
            { text: '常规', id: 'general' },
            { text: '高级', id: 'adv' }
          ]
        },
        { text: '帮助', id: 'help', url: 'https://help.example.com' }
      ]
    }
  ];
}

Component Methods

组件方法

Method: enableItems

方法:enableItems

Signature:
typescript
enableItems(items: string[], enable?: boolean, isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
string[]
NoArray of item text or ids that needs to be enabled/disabled.
enable
boolean
Yes, default:
true
Set
true
to enable items; set
false
to disable items.
isUniqueId
boolean
Yes, default:
false
Set
true
if items array contains unique ids instead of text.
Return:
void
Brief Example:
typescript
// Disable 'Delete' item by text
this.contextMenu.enableItems(['Delete'], false);

// Enable items by id
this.contextMenu.enableItems(['edit-item', 'copy-item'], true, true);
Full Working Example:
typescript
@Component({
  selector: 'app-enable-items',
  template: `
    <button (click)="disableDelete()">Disable Delete</button>
    <button (click)="enableAll()">Enable All</button>
    <div id="target">Right click here</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class EnableItemsComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [
    { text: 'Edit', id: 'edit' },
    { text: 'Delete', id: 'delete' },
    { text: 'Copy', id: 'copy' }
  ];
  
  disableDelete() {
    this.contextMenu.enableItems(['Delete'], false);
  }
  
  enableAll() {
    this.contextMenu.enableItems(['Edit', 'Delete', 'Copy'], true);
  }
}
签名:
typescript
enableItems(items: string[], enable?: boolean, isUniqueId?: boolean): void
参数类型可选描述
items
string[]
需要启用/禁用的项文本或ID数组。
enable
boolean
是,默认值:
true
设为
true
启用项;设为
false
禁用项。
isUniqueId
boolean
是,默认值:
false
如果items数组包含唯一ID而非文本,设为
true
返回值:
void
简要示例:
typescript
// 通过文本禁用“删除”项
this.contextMenu.enableItems(['Delete'], false);

// 通过ID启用项
this.contextMenu.enableItems(['edit-item', 'copy-item'], true, true);
完整运行示例:
typescript
@Component({
  selector: 'app-enable-items',
  template: `
    <button (click)="disableDelete()">禁用删除</button>
    <button (click)="enableAll()">启用全部</button>
    <div id="target">右键点击此处</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class EnableItemsComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [
    { text: '编辑', id: 'edit' },
    { text: '删除', id: 'delete' },
    { text: '复制', id: 'copy' }
  ];
  
  disableDelete() {
    this.contextMenu.enableItems(['Delete'], false);
  }
  
  enableAll() {
    this.contextMenu.enableItems(['Edit', 'Delete', 'Copy'], true);
  }
}

Method: insertAfter

方法:insertAfter

Signature:
typescript
insertAfter(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
MenuItemModel[]
NoArray of MenuItemModel that needs to be inserted.
text
string
NoText item after which the element to be inserted. If
isUniqueId
is true, this is the unique id.
isUniqueId
boolean
Yes, default:
false
Set
true
if text is a unique id instead of display text.
Return:
void
Brief Example:
typescript
// Insert item after 'Edit'
this.contextMenu.insertAfter([{ text: 'Save' }], 'Edit');

// Insert after item with specific id
this.contextMenu.insertAfter([{ text: 'New', id: 'new-item' }], 'edit-item', true);
Full Working Example:
typescript
@Component({
  selector: 'app-insert-after',
  template: `
    <button (click)="addAfterEdit()">Add Item After Edit</button>
    <div id="target">Right click here</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class InsertAfterComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [
    { text: 'Edit', id: 'edit' },
    { text: 'Delete', id: 'delete' }
  ];
  
  addAfterEdit() {
    this.contextMenu.insertAfter(
      [
        { text: 'Copy', id: 'copy' },
        { text: 'Paste', id: 'paste' }
      ],
      'Edit'
    );
  }
}
签名:
typescript
insertAfter(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
参数类型可选描述
items
MenuItemModel[]
需要插入的MenuItemModel数组。
text
string
要在其后插入元素的文本项。如果
isUniqueId
为true,则此为唯一ID。
isUniqueId
boolean
是,默认值:
false
如果text是唯一ID而非显示文本,设为
true
返回值:
void
简要示例:
typescript
// 在“编辑”后插入项
this.contextMenu.insertAfter([{ text: '保存' }], 'Edit');

// 在特定ID的项后插入
this.contextMenu.insertAfter([{ text: '新建', id: 'new-item' }], 'edit-item', true);
完整运行示例:
typescript
@Component({
  selector: 'app-insert-after',
  template: `
    <button (click)="addAfterEdit()">在编辑后添加项</button>
    <div id="target">右键点击此处</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class InsertAfterComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [
    { text: '编辑', id: 'edit' },
    { text: '删除', id: 'delete' }
  ];
  
  addAfterEdit() {
    this.contextMenu.insertAfter(
      [
        { text: '复制', id: 'copy' },
        { text: '粘贴', id: 'paste' }
      ],
      'Edit'
    );
  }
}

Method: insertBefore

方法:insertBefore

Signature:
typescript
insertBefore(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
MenuItemModel[]
NoArray of MenuItemModel that needs to be inserted.
text
string
NoText item before which the element to be inserted. If
isUniqueId
is true, this is the unique id.
isUniqueId
boolean
Yes, default:
false
Set
true
if text is a unique id instead of display text.
Return:
void
Brief Example:
typescript
this.contextMenu.insertBefore([{ text: 'Undo' }], 'Edit');
签名:
typescript
insertBefore(items: MenuItemModel[], text: string, isUniqueId?: boolean): void
参数类型可选描述
items
MenuItemModel[]
需要插入的MenuItemModel数组。
text
string
要在其前插入元素的文本项。如果
isUniqueId
为true,则此为唯一ID。
isUniqueId
boolean
是,默认值:
false
如果text是唯一ID而非显示文本,设为
true
返回值:
void
简要示例:
typescript
this.contextMenu.insertBefore([{ text: '撤销' }], 'Edit');

Method: removeItems

方法:removeItems

Signature:
typescript
removeItems(items: string[], isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
string[]
NoArray of item text or ids that needs to be removed.
isUniqueId
boolean
Yes, default:
false
Set
true
if items array contains unique ids instead of text.
Return:
void
Brief Example:
typescript
this.contextMenu.removeItems(['Delete', 'Copy']);
签名:
typescript
removeItems(items: string[], isUniqueId?: boolean): void
参数类型可选描述
items
string[]
需要移除的项文本或ID数组。
isUniqueId
boolean
是,默认值:
false
如果items数组包含唯一ID而非文本,设为
true
返回值:
void
简要示例:
typescript
this.contextMenu.removeItems(['Delete', 'Copy']);

Method: hideItems

方法:hideItems

Signature:
typescript
hideItems(items: string[], isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
string[]
NoArray of item text or ids that needs to be hidden.
isUniqueId
boolean
Yes, default:
false
Set
true
if items array contains unique ids instead of text.
Return:
void
Brief Example:
typescript
this.contextMenu.hideItems(['AdminOnly'], true);
签名:
typescript
hideItems(items: string[], isUniqueId?: boolean): void
参数类型可选描述
items
string[]
需要隐藏的项文本或ID数组。
isUniqueId
boolean
是,默认值:
false
如果items数组包含唯一ID而非文本,设为
true
返回值:
void
简要示例:
typescript
this.contextMenu.hideItems(['AdminOnly'], true);

Method: showItems

方法:showItems

Signature:
typescript
showItems(items: string[], isUniqueId?: boolean): void
ParameterTypeOptionalDescription
items
string[]
NoArray of item text or ids that needs to be shown.
isUniqueId
boolean
Yes, default:
false
Set
true
if items array contains unique ids instead of text.
Return:
void
Brief Example:
typescript
this.contextMenu.showItems(['AdminOnly'], true);
签名:
typescript
showItems(items: string[], isUniqueId?: boolean): void
参数类型可选描述
items
string[]
需要显示的项文本或ID数组。
isUniqueId
boolean
是,默认值:
false
如果items数组包含唯一ID而非文本,设为
true
返回值:
void
简要示例:
typescript
this.contextMenu.showItems(['AdminOnly'], true);

Method: getItemIndex

方法:getItemIndex

Signature:
typescript
getItemIndex(item: MenuItem | string, isUniqueId?: boolean): number[]
ParameterTypeOptionalDescription
item
MenuItem | string
NoMenuItem object or id/text to get the index for.
isUniqueId
boolean
Yes, default:
false
Set
true
if item is a unique id instead of text.
Return:
number[]
- Array of indices representing the position of the item in the menu hierarchy.
Brief Example:
typescript
// Get index by text
const index = this.contextMenu.getItemIndex('Edit'); // [0] for first item

// Get index by id
const index = this.contextMenu.getItemIndex('edit-item', true); // [0]

// For nested items
const index = this.contextMenu.getItemIndex('Bold', true); // [1, 0] for Format > Bold
Full Working Example:
typescript
@Component({
  selector: 'app-get-index',
  template: `
    <button (click)="findItem()">Find Item Index</button>
    <div>Index: {{ itemIndex }}</div>
    <div id="target">Right click here</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class GetIndexComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  itemIndex: any = null;
  
  items: MenuItemModel[] = [
    { text: 'Edit', id: 'edit' },
    {
      text: 'Format',
      id: 'format',
      items: [
        { text: 'Bold', id: 'bold' },
        { text: 'Italic', id: 'italic' }
      ]
    }
  ];
  
  findItem() {
    this.itemIndex = this.contextMenu.getItemIndex('Bold', true);
    console.log('Item index:', this.itemIndex); // [1, 0]
  }
}
签名:
typescript
getItemIndex(item: MenuItem | string, isUniqueId?: boolean): number[]
参数类型可选描述
item
MenuItem | string
MenuItem对象或用于获取索引的ID/文本。
isUniqueId
boolean
是,默认值:
false
如果item是唯一ID而非文本,设为
true
返回值:
number[]
- 表示项在菜单层级中位置的索引数组。
简要示例:
typescript
// 通过文本获取索引
const index = this.contextMenu.getItemIndex('Edit'); // 第一个项为[0]

// 通过ID获取索引
const index = this.contextMenu.getItemIndex('edit-item', true); // [0]

// 嵌套项的索引
const index = this.contextMenu.getItemIndex('Bold', true); // 格式>加粗为[1, 0]
完整运行示例:
typescript
@Component({
  selector: 'app-get-index',
  template: `
    <button (click)="findItem()">查找项索引</button>
    <div>索引: {{ itemIndex }}</div>
    <div id="target">右键点击此处</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class GetIndexComponent {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  itemIndex: any = null;
  
  items: MenuItemModel[] = [
    { text: '编辑', id: 'edit' },
    {
      text: '格式',
      id: 'format',
      items: [
        { text: '加粗', id: 'bold' },
        { text: '斜体', id: 'italic' }
      ]
    }
  ];
  
  findItem() {
    this.itemIndex = this.contextMenu.getItemIndex('Bold', true);
    console.log('项索引:', this.itemIndex); // [1, 0]
  }
}

Method: setItem

方法:setItem

Signature:
typescript
setItem(item: MenuItem, id?: string, isUniqueId?: boolean): void
ParameterTypeOptionalDescription
item
MenuItem
NoMenuItem object containing updated properties.
id
string
Yesid or text of the item to be updated. If not provided, updates the item passed as first parameter.
isUniqueId
boolean
Yes, default:
false
Set
true
if id is a unique id instead of text.
Return:
void
Brief Example:
typescript
// Update item by text
this.contextMenu.setItem({ text: 'Edit Document' }, 'Edit');

// Update item by id
this.contextMenu.setItem(
  { text: 'Remove', iconCss: 'e-icons e-delete' },
  'delete-item',
  true
);
签名:
typescript
setItem(item: MenuItem, id?: string, isUniqueId?: boolean): void
参数类型可选描述
item
MenuItem
包含更新属性的MenuItem对象。
id
string
要更新的项的ID或文本。如果未提供,则更新作为第一个参数传入的项。
isUniqueId
boolean
是,默认值:
false
如果id是唯一ID而非文本,设为
true
返回值:
void
简要示例:
typescript
// 通过文本更新项
this.contextMenu.setItem({ text: '编辑文档' }, 'Edit');

// 通过ID更新项
this.contextMenu.setItem(
  { text: '移除', iconCss: 'e-icons e-delete' },
  'delete-item',
  true
);

Method: open

方法:open

Signature:
typescript
open(top: number, left: number, target?: HTMLElement): void
ParameterTypeOptionalDescription
top
number
NoTo specify ContextMenu vertical positioning (Y coordinate in pixels).
left
number
NoTo specify ContextMenu horizontal positioning (X coordinate in pixels).
target
HTMLElement
YesTo calculate z-index for ContextMenu based upon the specified target element.
Return:
void
Brief Example:
typescript
// Open at mouse position
this.contextMenu.open(event.clientY, event.clientX);

// Open at specific coordinates
this.contextMenu.open(200, 300);

// Open relative to target element
this.contextMenu.open(100, 150, document.getElementById('target'));
签名:
typescript
open(top: number, left: number, target?: HTMLElement): void
参数类型可选描述
top
number
指定ContextMenu的垂直位置(像素为单位的Y坐标)。
left
number
指定ContextMenu的水平位置(像素为单位的X坐标)。
target
HTMLElement
根据指定的目标元素计算ContextMenu的z-index。
返回值:
void
简要示例:
typescript
// 在鼠标位置打开
this.contextMenu.open(event.clientY, event.clientX);

// 在特定坐标打开
this.contextMenu.open(200, 300);

// 相对于目标元素打开
this.contextMenu.open(100, 150, document.getElementById('target'));

Method: close

方法:close

Signature:
typescript
close(): void
Parameter---
Return:
void
Brief Example:
typescript
// Close the open ContextMenu
this.contextMenu.close();
签名:
typescript
close(): void
参数---
返回值:
void
简要示例:
typescript
// 关闭打开的ContextMenu
this.contextMenu.close();

Method: destroy

方法:destroy

Signature:
typescript
destroy(): void
Parameter---
Return:
void
Brief Example:
typescript
// Completely destroy the component and cleanup resources
this.contextMenu.destroy();
Full Working Example - Destroy on Component Destroy:
typescript
import { Component, ViewChild, OnDestroy } from '@angular/core';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';

@Component({
  selector: 'app-destroy-example',
  template: `
    <button (click)="destroyMenu()">Destroy Menu</button>
    <div id="target">Right click here</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class DestroyExampleComponent implements OnDestroy {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [{ text: 'Item 1' }];
  
  destroyMenu() {
    if (this.contextMenu) {
      this.contextMenu.destroy();
      console.log('Menu destroyed');
    }
  }
  
  ngOnDestroy() {
    // Cleanup when component is destroyed
    if (this.contextMenu) {
      this.contextMenu.destroy();
    }
  }
}
签名:
typescript
destroy(): void
参数---
返回值:
void
简要示例:
typescript
// 完全销毁组件并清理资源
this.contextMenu.destroy();
完整运行示例 - 组件销毁时销毁菜单:
typescript
import { Component, ViewChild, OnDestroy } from '@angular/core';
import { ContextMenuComponent } from '@syncfusion/ej2-angular-navigations';

@Component({
  selector: 'app-destroy-example',
  template: `
    <button (click)="destroyMenu()">销毁菜单</button>
    <div id="target">右键点击此处</div>
    <ejs-contextmenu #cm target='#target' [items]='items'></ejs-contextmenu>
  `
})
export class DestroyExampleComponent implements OnDestroy {
  @ViewChild('cm') contextMenu!: ContextMenuComponent;
  items: MenuItemModel[] = [{ text: '项1' }];
  
  destroyMenu() {
    if (this.contextMenu) {
      this.contextMenu.destroy();
      console.log('菜单已销毁');
    }
  }
  
  ngOnDestroy() {
    // 组件销毁时清理
    if (this.contextMenu) {
      this.contextMenu.destroy();
    }
  }
}

Animation Settings (MenuAnimationSettingsModel)

动画设置(MenuAnimationSettingsModel)

Configure how menu items animate when opening/closing:
PropertyTypeDefaultDescription
duration
number
400
Specifies the time duration (in milliseconds) to transform/animate the menu. Example:
300
for 300ms animation.
easing
string
'ease'
Specifies the easing effect applied while transform. Examples:
'ease'
,
'ease-in'
,
'ease-out'
,
'ease-in-out'
,
'linear'
,
'cubic-bezier(0.25, 0.1, 0.25, 1)'
.
effect
MenuEffect
'SlideDown'
Specifies the effect that shown in the sub menu transform. Options:
'None' | 'SlideDown' | 'ZoomIn' | 'FadeIn'
.
Effect Options:
  • None: Specifies the sub menu transform with no animation effect.
  • SlideDown: Specifies the sub menu transform with slide down effect (default).
  • ZoomIn: Specifies the sub menu transform with zoom in effect.
  • FadeIn: Specifies the sub menu transform with fade in effect.
Brief Example:
typescript
animationSettings = {
  duration: 300,
  effect: 'FadeIn' as any,
  easing: 'ease-out'
};
Full Working Example:
typescript
@Component({
  selector: 'app-animation-config',
  template: `
    <div id="target">Right click here</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      [animationSettings]='animSettings'>
    </ejs-contextmenu>
  `
})
export class AnimationConfigComponent {
  items: MenuItemModel[] = [
    { text: 'Option 1' },
    { text: 'Option 2' }
  ];
  
  animSettings = {
    effect: 'ZoomIn' as any,
    duration: 200,
    easing: 'ease-in-out'
  };
}
配置菜单项打开/关闭时的动画效果:
属性类型默认值描述
duration
number
400
指定菜单变换/动画的持续时间(毫秒),示例:
300
表示300毫秒动画。
easing
string
'ease'
指定变换时应用的缓动效果,示例:
'ease'
'ease-in'
'ease-out'
'ease-in-out'
'linear'
'cubic-bezier(0.25, 0.1, 0.25, 1)'
effect
MenuEffect
'SlideDown'
指定子菜单变换时显示的效果,选项:
'None' | 'SlideDown' | 'ZoomIn' | 'FadeIn'
效果选项:
  • None: 指定子菜单变换时无动画效果。
  • SlideDown: 指定子菜单变换时使用向下滑动效果(默认)。
  • ZoomIn: 指定子菜单变换时使用放大效果。
  • FadeIn: 指定子菜单变换时使用淡入效果。
简要示例:
typescript
animationSettings = {
  duration: 300,
  effect: 'FadeIn' as any,
  easing: 'ease-out'
};
完整运行示例:
typescript
@Component({
  selector: 'app-animation-config',
  template: `
    <div id="target">右键点击此处</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      [animationSettings]='animSettings'>
    </ejs-contextmenu>
  `
})
export class AnimationConfigComponent {
  items: MenuItemModel[] = [
    { text: '选项1' },
    { text: '选项2' }
  ];
  
  animSettings = {
    effect: 'ZoomIn' as any,
    duration: 200,
    easing: 'ease-in-out'
  };
}

Component Events

组件事件

Event: beforeOpen

事件:beforeOpen

Signature:
(beforeOpen): EmitType<BeforeOpenCloseMenuEventArgs>
Triggers before opening the menu item. Use this to prevent menu opening, show/hide items based on context, or customize menu before display.
Event Arguments - BeforeOpenCloseMenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'beforeOpen'
).
Brief Example:
typescript
onBeforeOpen(args: BeforeOpenCloseMenuEventArgs) {
  console.log('Menu about to open');
}
Full Working Example:
typescript
@Component({
  selector: 'app-before-open',
  template: `
    <div id="target">Right click to open</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (beforeOpen)='onBeforeOpen($event)'>
    </ejs-contextmenu>
  `
})
export class BeforeOpenComponent {
  items: MenuItemModel[] = [{ text: 'Item 1' }];
  
  onBeforeOpen(args: BeforeOpenCloseMenuEventArgs) {
    console.log('Event:', args.name); // 'beforeOpen'
  }
}
签名:
(beforeOpen): EmitType<BeforeOpenCloseMenuEventArgs>
在菜单项打开前触发,可用于阻止菜单打开、根据上下文显示/隐藏项或在显示前自定义菜单。
事件参数 - BeforeOpenCloseMenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'beforeOpen'
)。
简要示例:
typescript
onBeforeOpen(args: BeforeOpenCloseMenuEventArgs) {
  console.log('菜单即将打开');
}
完整运行示例:
typescript
@Component({
  selector: 'app-before-open',
  template: `
    <div id="target">右键点击打开</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (beforeOpen)='onBeforeOpen($event)'>
    </ejs-contextmenu>
  `
})
export class BeforeOpenComponent {
  items: MenuItemModel[] = [{ text: '项1' }];
  
  onBeforeOpen(args: BeforeOpenCloseMenuEventArgs) {
    console.log('事件:', args.name); // 'beforeOpen'
  }
}

Event: beforeClose

事件:beforeClose

Signature:
(beforeClose): EmitType<BeforeOpenCloseMenuEventArgs>
Triggers before closing the menu. Use this to perform cleanup or prevent menu from closing.
Event Arguments - BeforeOpenCloseMenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'beforeClose'
).
Brief Example:
typescript
onBeforeClose(args: BeforeOpenCloseMenuEventArgs) {
  console.log('Menu about to close');
}
签名:
(beforeClose): EmitType<BeforeOpenCloseMenuEventArgs>
在菜单关闭前触发,可用于执行清理操作或阻止菜单关闭。
事件参数 - BeforeOpenCloseMenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'beforeClose'
)。
简要示例:
typescript
onBeforeClose(args: BeforeOpenCloseMenuEventArgs) {
  console.log('菜单即将关闭');
}

Event: onOpen

事件:onOpen

Signature:
(onOpen): EmitType<OpenCloseMenuEventArgs>
Triggers while opening the menu item. This event fires after the menu has been opened and is visible.
Event Arguments - OpenCloseMenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'onOpen'
).
Brief Example:
typescript
onOpen(args: OpenCloseMenuEventArgs) {
  console.log('Menu opened:', args.name);
}
Full Working Example:
typescript
@Component({
  selector: 'app-open-event',
  template: `
    <div id="target">Right click here</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (onOpen)='onOpen($event)'
      (onClose)='onClose($event)'>
    </ejs-contextmenu>
    <p>Status: {{ menuStatus }}</p>
  `
})
export class OpenEventComponent {
  items: MenuItemModel[] = [{ text: 'Item 1' }];
  menuStatus = 'Closed';
  
  onOpen(args: OpenCloseMenuEventArgs) {
    this.menuStatus = 'Menu Opened - ' + args.name;
  }
  
  onClose(args: OpenCloseMenuEventArgs) {
    this.menuStatus = 'Menu Closed - ' + args.name;
  }
}
签名:
(onOpen): EmitType<OpenCloseMenuEventArgs>
在菜单项打开时触发,此事件在菜单已打开并可见后触发。
事件参数 - OpenCloseMenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'onOpen'
)。
简要示例:
typescript
onOpen(args: OpenCloseMenuEventArgs) {
  console.log('菜单已打开:', args.name);
}
完整运行示例:
typescript
@Component({
  selector: 'app-open-event',
  template: `
    <div id="target">右键点击此处</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (onOpen)='onOpen($event)'
      (onClose)='onClose($event)'>
    </ejs-contextmenu>
    <p>状态: {{ menuStatus }}</p>
  `
})
export class OpenEventComponent {
  items: MenuItemModel[] = [{ text: '项1' }];
  menuStatus = '已关闭';
  
  onOpen(args: OpenCloseMenuEventArgs) {
    this.menuStatus = '菜单已打开 - ' + args.name;
  }
  
  onClose(args: OpenCloseMenuEventArgs) {
    this.menuStatus = '菜单已关闭 - ' + args.name;
  }
}

Event: onClose

事件:onClose

Signature:
(onClose): EmitType<OpenCloseMenuEventArgs>
Triggers while closing the menu. This event fires after the menu has been closed and is no longer visible.
Event Arguments - OpenCloseMenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'onClose'
).
Brief Example:
typescript
onClose(args: OpenCloseMenuEventArgs) {
  console.log('Menu closed:', args.name);
}
签名:
(onClose): EmitType<OpenCloseMenuEventArgs>
在菜单关闭时触发,此事件在菜单已关闭且不可见后触发。
事件参数 - OpenCloseMenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'onClose'
)。
简要示例:
typescript
onClose(args: OpenCloseMenuEventArgs) {
  console.log('菜单已关闭:', args.name);
}

Event: select

事件:select

Signature:
(select): EmitType<MenuEventArgs>
Triggers while selecting menu item. Use this to handle menu item clicks and perform actions.
Event Arguments - MenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'select'
).
Brief Example:
typescript
onSelect(args: MenuEventArgs) {
  console.log('Item selected:', args.name);
}
Full Working Example:
typescript
@Component({
  selector: 'app-select-event',
  template: `
    <div id="target">Right click here</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (select)='onSelect($event)'>
    </ejs-contextmenu>
    <p>Selected: {{ selectedItem }}</p>
  `
})
export class SelectEventComponent {
  items: MenuItemModel[] = [
    { text: 'Edit', id: 'edit' },
    { text: 'Delete', id: 'delete' },
    { text: 'Copy', id: 'copy' }
  ];
  
  selectedItem = 'None';
  
  onSelect(args: MenuEventArgs) {
    this.selectedItem = args.name;
    console.log('Selected item event:', args.name);
  }
}
签名:
(select): EmitType<MenuEventArgs>
在选择菜单项时触发,可用于处理菜单项点击并执行操作。
事件参数 - MenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'select'
)。
简要示例:
typescript
onSelect(args: MenuEventArgs) {
  console.log('项已选中:', args.name);
}
完整运行示例:
typescript
@Component({
  selector: 'app-select-event',
  template: `
    <div id="target">右键点击此处</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (select)='onSelect($event)'>
    </ejs-contextmenu>
    <p>已选中: {{ selectedItem }}</p>
  `
})
export class SelectEventComponent {
  items: MenuItemModel[] = [
    { text: '编辑', id: 'edit' },
    { text: '删除', id: 'delete' },
    { text: '复制', id: 'copy' }
  ];
  
  selectedItem = '无';
  
  onSelect(args: MenuEventArgs) {
    this.selectedItem = args.name;
    console.log('选中项事件:', args.name);
  }
}

Event: beforeItemRender

事件:beforeItemRender

Signature:
(beforeItemRender): EmitType<MenuEventArgs>
Triggers while rendering each menu item. Use this to customize each item's appearance or behavior before rendering.
Event Arguments - MenuEventArgs:
PropertyTypeDescription
name
string
Specifies name of the event (value:
'beforeItemRender'
).
Brief Example:
typescript
onBeforeItemRender(args: MenuEventArgs) {
  console.log('Rendering item:', args.name);
}
Full Working Example:
typescript
@Component({
  selector: 'app-before-item-render',
  template: `
    <div id="target">Right click here</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (beforeItemRender)='onBeforeItemRender($event)'>
    </ejs-contextmenu>
  `
})
export class BeforeItemRenderComponent {
  items: MenuItemModel[] = [
    { text: 'Edit', id: 'edit' },
    { text: 'Delete', id: 'delete' }
  ];
  
  onBeforeItemRender(args: MenuEventArgs) {
    console.log('Rendering:', args.name);
    // Customize items before rendering
  }
}
签名:
(beforeItemRender): EmitType<MenuEventArgs>
在渲染每个菜单项时触发,可用于在渲染前自定义每个项的外观或行为。
事件参数 - MenuEventArgs:
属性类型描述
name
string
指定事件名称(值:
'beforeItemRender'
)。
简要示例:
typescript
onBeforeItemRender(args: MenuEventArgs) {
  console.log('正在渲染项:', args.name);
}
完整运行示例:
typescript
@Component({
  selector: 'app-before-item-render',
  template: `
    <div id="target">右键点击此处</div>
    <ejs-contextmenu 
      target='#target' 
      [items]='items'
      (beforeItemRender)='onBeforeItemRender($event)'>
    </ejs-contextmenu>
  `
})
export class BeforeItemRenderComponent {
  items: MenuItemModel[] = [
    { text: '编辑', id: 'edit' },
    { text: '删除', id: 'delete' }
  ];
  
  onBeforeItemRender(args: MenuEventArgs) {
    console.log('正在渲染:', args.name);
    // 渲染前自定义项
  }
}

Event: created

事件:created

Signature:
(created): EmitType<Event>
Triggers once the component rendering is completed. Use this for post-initialization setup.
Event Arguments:
PropertyTypeDescription
-
Event
Standard JavaScript Event object.
Brief Example:
typescript
onCreated(event: Event) {
  console.log('ContextMenu component created and ready');
}

签名:
(created): EmitType<Event>
组件渲染完成后触发一次,可用于初始化后的设置。
事件参数:
属性类型描述
-
Event
标准JavaScript Event对象。
简要示例:
typescript
onCreated(event: Event) {
  console.log('ContextMenu组件已创建并就绪');
}

Key Properties & Events Quick Reference

关键属性与事件快速参考

Property/EventPurposeExample
items
Define menu structure
items: MenuItemModel[]
target
Element triggering menu
target='#target'
select
Menu item click
(select)="onSelect($event)"
beforeOpen
Before menu opens
(beforeOpen)="onBeforeOpen($event)"
enableItems()
Toggle item availability
enableItems(['Edit'], false)
insertAfter()
Add items after target
insertAfter([...], 'Refresh')
hideItems()
Hide specific items
hideItems(['Cut', 'Copy'])
animationSettings
Control appearance effects
animationSettings: {...}
属性/事件用途示例
items
定义菜单结构
items: MenuItemModel[]
target
触发菜单的元素
target='#target'
select
菜单项点击
(select)="onSelect($event)"
beforeOpen
菜单打开前
(beforeOpen)="onBeforeOpen($event)"
enableItems()
切换项可用性
enableItems(['Edit'], false)
insertAfter()
在目标后添加项
insertAfter([...], 'Refresh')
hideItems()
隐藏特定项
hideItems(['Cut', 'Copy'])
animationSettings
控制外观效果
animationSettings: {...}

Common Use Cases

常见用例

  1. File Operations Menu - Cut, Copy, Paste, Delete options
  2. Content Editor Menu - Format, Insert, Link, Media options
  3. Data Grid Context - Edit, Delete, Export, Filter actions
  4. Navigation Menu - Links to pages or external URLs
  5. Permission-Based Menu - Show/hide items based on user role
  6. Multi-Language Menu - Dynamic item text from translations
  7. Confirmation Dialogs - Open dialog before executing action
  8. Table Operations - Row/column management in data tables
  1. 文件操作菜单 - 剪切、复制、粘贴、删除选项
  2. 内容编辑器菜单 - 格式、插入、链接、媒体选项
  3. 数据网格上下文 - 编辑、删除、导出、筛选操作
  4. 导航菜单 - 指向页面或外部URL的链接
  5. 基于权限的菜单 - 根据用户角色显示/隐藏项
  6. 多语言菜单 - 来自翻译的动态项文本
  7. 确认对话框 - 执行操作前打开对话框
  8. 表格操作 - 数据表中的行/列管理

Next Steps

后续步骤

  1. Select a reference file based on your task (Getting Started, Menu Management, Data Binding, Events, Styling, or Templates)
  2. Review the code examples for your specific use case
  3. Copy relevant code patterns to your project
  4. Customize menu items for your application context
  5. Test interactions with different target elements

Need help with a specific task? Reference the appropriate guide above and let me know which menu feature you're implementing.
  1. 根据你的任务选择参考文件(快速入门、菜单管理、数据绑定、事件、样式或模板)
  2. 查看针对你的特定用例的代码示例
  3. 将相关代码模式复制到你的项目中
  4. 针对你的应用上下文自定义菜单项
  5. 测试与不同目标元素的交互

需要特定任务的帮助? 参考上述相应指南,并告诉我你正在实现哪个菜单功能。