1

So it is clear how to get an index value for the rows when rendering a table according to the guide for Angular Material .. you can do this

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

But what about the index for the column? it seems tricky because we are not using any traditional for loops to generate the columns but rather we are assigning it directly in *matRowDef as you see above.

And we are defining our columns like this..

<ng-container matColumnDef="returnToService"> 
            <th mat-header-cell *matHeaderCellDef mat-sort-header> 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 mat-sort-header> Work Order Reported Date </th>
            <td mat-cell *matCellDef="let workOrder"> {{formatDate(workOrder.requestDate)}}  </td>
  </ng-container>

I see no way of getting index in *matHeaderRowDef here..

 <tr mat-header-row *matHeaderRowDef="displayedColumns; let i = ???" (click)="debug(??)"></tr>
 <tr mat-row *matRowDef="let row; columns: displayedColumns;let i = index" (click)="debug(i)"></tr>
LukePerrin
  • 235
  • 5
  • 17

1 Answers1

1

Looks like only matCellDef and matRowDef export any position context, and even then it is only row context, not column. They describe it briefly on the CdkTable overview, which is what the MatTable is derived from: https://material.angular.io/cdk/table/overview

So you'll have to just get the index yourself from the name. It's unlikely there will be a significant number of columns, so a brute force search of the array is probably fine.

TS

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

HTML - example column

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

Live example: https://stackblitz.com/edit/angular-m9atjw?file=src/app/table-basic-example.html

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26