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

Angular Material:为mat-row添加点击触发的mat-menu

解决方案

步骤1:将mat-menu移到组件根层级(脱离matColumnDef)

不需要把菜单嵌套在列定义内部,直接放在表格外的组件模板区域,这样mat-row就能直接引用到菜单的模板变量。同时通过let-report="report"接收后续传递的行数据:

<!-- 放在表格外的组件根区域 -->
<mat-menu #reportMenu="matMenu">
  <div>{{ report.name }}</div>
  <!-- 可按需添加更多菜单项 -->
  <button mat-menu-item>查看详情</button>
</mat-menu>

步骤2:给mat-row绑定菜单触发并传递行数据

在mat-row上添加菜单触发指令,同时用matMenuTriggerData把当前行的row(即对应的report对象)传递给菜单:

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef>ID</th>
    <td mat-cell *matCellDef="let report" [innerText]="report.id"></td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="['id']"></tr>
  <!-- 为行添加菜单触发逻辑 -->
  <tr 
    mat-row 
    *matRowDef="let row; columns: ['id'];"
    [matMenuTriggerFor]="reportMenu"
    [matMenuTriggerData]="{ report: row }"
  ></tr>
</table>

原理说明

  • matMenuTriggerData会将指定对象注入菜单的模板上下文,菜单内通过let-report="report"即可获取该行对应的report数据。
  • 把菜单放在根层级后,mat-row能直接引用#reportMenu模板变量,解决了跨matColumnDef无法引用的问题。

可选优化:自定义触发区域

如果不想点击整行触发菜单,可以新增一个操作列,用按钮作为触发点:

<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef>操作</th>
  <td mat-cell *matCellDef="let report">
    <button mat-icon-button 
            [matMenuTriggerFor]="reportMenu" 
            [matMenuTriggerData]="{ report: report }">
      <mat-icon>more_vert</mat-icon>
    </button>
  </td>
</ng-container>

<!-- 行定义需新增actions列 -->
<tr mat-row *matRowDef="let row; columns: ['id', 'actions'];"></tr>

内容的提问来源于stack exchange,提问作者Hasan Can Saral

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:35:33