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

如何在Angular Material matTable中获取列索引?

Angular Material表格获取列索引的解决方法

在Angular Material表格中,行索引可以通过*matRowDef的index变量直接获取,但列索引的获取因为采用matColumnDef定义列、displayedColumns数组控制渲染的方式,无法直接在*matHeaderRowDef中拿到,以下分场景给出具体实现方案:

一、获取单个表头单元格的列索引

方法1:通过列名映射索引

在组件中定义方法,根据列名返回其在displayedColumns数组中的索引:

getColumnIndex(columnName: string): number {
  return this.displayedColumns.indexOf(columnName);
}

在表头单元格模板中,利用*matHeaderCellDef暴露的col变量(当前列名称)调用该方法:

<ng-container matColumnDef="returnToService"> 
  <th mat-header-cell *matHeaderCellDef="let column = col" mat-sort-header (click)="debug(getColumnIndex(column))"> Returned To Service </th>
  <td mat-cell *matCellDef="let workOrder"> {{formatDate(workOrder.returnToService)}} </td>
</ng-container>

<ng-container matColumnDef="requestDate">
  <th mat-header-cell *matHeaderCellDef="let column = col" mat-sort-header (click)="debug(getColumnIndex(column))"> Work Order Reported Date </th>
  <td mat-cell *matCellDef="let workOrder"> {{formatDate(workOrder.requestDate)}} </td>
</ng-container>

方法2:通过事件委托获取表头行点击的列索引

如果需要在整个表头行的点击事件中获取列索引,可通过事件委托实现:
模板代码:

<tr mat-header-row *matHeaderRowDef="displayedColumns" (click)="onHeaderRowClick($event)"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns; let i = index" (click)="debug(i)"></tr>

组件逻辑:

onHeaderRowClick(event: MouseEvent): void {
  const target = event.target as HTMLElement;
  const headerCell = target.closest('th[mat-header-cell]');
  if (!headerCell) return;
  
  const columnName = headerCell.getAttribute('mat-column-def');
  if (!columnName) return;
  
  const columnIndex = this.displayedColumns.indexOf(columnName);
  this.debug(columnIndex);
}

二、获取数据行单元格的列索引

类似表头的处理逻辑,在mat-cell模板中结合col变量和组件方法获取索引:

<ng-container matColumnDef="returnToService"> 
  <th mat-header-cell *matHeaderCellDef="let column = col" mat-sort-header> Returned To Service </th>
  <td mat-cell *matCellDef="let workOrder; let column = col" (click)="debug(getColumnIndex(column))"> {{formatDate(workOrder.returnToService)}} </td>
</ng-container>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:35:09