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

Angular 9 如何为mat-table的每一行添加操作按钮

问题原因&修复方案

  • 操作列定义不符合Angular 9对应Angular Material版本的规范:当前使用的<mat-header-cell>、<mat-cell>标签写法缺少必填的结构指令*matHeaderCellDef、*matCellDef,Angular 9版本更兼容<th mat-header-cell>、<td mat-cell>的属性式写法
  • 未将操作列加入显示列配置:表头行、数据行绑定的columnsToDisplay数组中没有添加actions字段,Angular Material表格仅会渲染该数组内声明的列
  • 按钮点击会冲突行展开逻辑:如果点击编辑按钮不需要触发行展开效果,需要给按钮添加事件阻止冒泡

具体修改步骤

  1. 更新ts文件中的列配置数组,加入actions字段,示例:
// 原写法示例,根据你的实际字段调整
columnsToDisplay = ['position', 'name', 'weight', 'symbol'];
// 修改后
columnsToDisplay = ['position', 'name', 'weight', 'symbol', 'actions'];
  1. 替换模板中的actions列定义代码,修正结构:
<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef> Actions </th>
  <td mat-cell *matCellDef="let row">
    <button mat-button (click)="$event.stopPropagation()">Edit</button>
  </td>
</ng-container>

修正后完整模板代码

<table mat-table
       [dataSource]="dataSource" multiTemplateDataRows
       class="mat-elevation-z8">
  <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <!-- 展开内容列 - 详情行占满所有列 -->
  <ng-container matColumnDef="expandedDetail">
    <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
      <div class="example-element-detail"
           [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
        <div class="example-element-diagram">
          <div class="example-element-position"> {{element.position}} </div>
          <div class="example-element-symbol"> {{element.symbol}} </div>
          <div class="example-element-name"> {{element.name}} </div>
          <div class="example-element-weight"> {{element.weight}} </div>
        </div>
        <div class="example-element-description">
          {{element.description}}
          <span class="example-element-description-attribution"> -- Wikipedia </span>
        </div>
      </div>
    </td>
  </ng-container>

  <ng-container matColumnDef="actions">
    <th mat-header-cell *matHeaderCellDef> Actions </th>
    <td mat-cell *matCellDef="let row">
      <button mat-button (click)="$event.stopPropagation()">Edit</button>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
</table>

内容的提问来源于stack exchange,提问作者Tony Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:45:06