0
votes

How can I get in a table made in Angular material the index of a clicked column?

I use <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true; let i = index;" (click)="clickEventT(i)"></tr>

but something missing.

1
Do you want to get index of column, when clicked on particular column ?GRD

1 Answers

0
votes

The <tr ...></tr> tag is actually the header row and not the header cell. Now the index of each header cell within the table depends on the displayedColumns ordering, depending on the use case it might be dynamically changing or not. An hardcoded solution could be perfectly valid as in many cases re-ordering columns wont happen.

<table mat-table [dataSource]="dataSource">
  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef (click)="showIndex('weight')"> Weight </th>
    <td mat-cell *matCellDef="let element" (click)="showIndex('weight')"> {{element.weight}} </td>
  </ng-container>
  <!-- ... -->
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

In scenarios where the displayed columns change The showIndex(columnName: string) function can display/return the column index as follows

displayedColumns: string[] = ['weight','...'];
showIndex(columnName: string): void {
   const index = this.displayedColumns.indexOf(columnName);
   console.log(index);
   alert(index);
}