You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular CDK上下文菜单:基于选中行动态生成菜单

如何基于选中行数据动态生成Angular CDK上下文菜单选项

要实现根据选中行数据动态生成上下文菜单,你可以按照以下步骤修改代码:

1. 组件中定义核心属性与逻辑

在组件类里添加选中行数据、菜单选项列表,以及根据选中行生成菜单的方法:

import { Component } from '@angular/core';
import { CdkContextMenuTrigger, CdkMenuItem, CdkMenu } from '@angular/cdk/menu';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  // 存储当前选中的行数据,实际场景替换为真实行对象
  selectedRowData: any;

  // 动态生成的菜单选项列表
  menuItems: Array<{ label: string; action: () => void; visible: boolean }> = [];

  // 根据选中行数据生成对应菜单选项
  generateMenuItems() {
    // 清空旧菜单
    this.menuItems = [];

    // 基础选项:所有行都显示
    this.menuItems.push({
      label: '复制',
      action: () => this.handleCopy(),
      visible: true
    });

    // 根据选中行权限显示编辑选项
    if (this.selectedRowData?.canEdit) {
      this.menuItems.push({
        label: '编辑',
        action: () => this.handleEdit(),
        visible: true
      });
    }

    // 根据选中行权限显示删除选项
    if (this.selectedRowData?.canDelete) {
      this.menuItems.push({
        label: '删除',
        action: () => this.handleDelete(),
        visible: true
      });
    }
  }

  // 菜单操作示例方法
  handleCopy() {
    console.log('复制选中行:', this.selectedRowData);
  }

  handleEdit() {
    console.log('编辑选中行:', this.selectedRowData);
  }

  handleDelete() {
    console.log('删除选中行:', this.selectedRowData);
  }

  // 选中行变化时更新菜单
  onRowSelect(rowData: any) {
    this.selectedRowData = rowData;
    this.generateMenuItems();
  }
}

2. 修改模板动态渲染菜单

在HTML模板中,通过*ngFor循环渲染动态生成的菜单选项,同时绑定行选中逻辑:

<!-- 表格行示例:右键点击时传递当前行数据并触发菜单 -->
<tr 
  (contextmenu)="onRowSelect(rowData)" 
  [cdkContextMenuTriggerFor]="context_menu"
>
  <td>{{ rowData.name }}</td>
  <!-- 其他列内容 -->
</tr>

<ng-template #context_menu>
  <div class="example-menu" cdkMenu>
    <!-- 动态渲染菜单选项 -->
    <button 
      *ngFor="let item of menuItems" 
      class="example-menu-item" 
      cdkMenuItem
      (click)="item.action()"
    >
      {{ item.label }}
    </button>
  </div>
</ng-template>

关键细节说明

  • 行数据传递:通过行的contextmenu事件,将当前右键点击的行数据传入组件,触发菜单重新生成。
  • 动态权限控制:在generateMenuItems方法中,根据选中行的属性(如canEdit、canDelete)决定是否添加对应菜单选项,实现按需显示。
  • 操作绑定:每个菜单按钮的点击事件直接绑定到对应处理方法,确保操作能获取到最新的选中行数据。

如果需要在菜单打开前才确认选中行,也可以通过contextMenuOpened事件触发更新:

<tr 
  [cdkContextMenuTriggerFor]="context_menu"
  (contextMenuOpened)="onRowSelect(rowData)"
>
  <!-- 列内容 -->
</tr>

内容的提问来源于stack exchange,提问作者Priya Ganesan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 03:42:23