Search code examples
javascriptangulartypescriptcheckboxmaterial-table

How to get row index in material table Angular


How to get row index in material table angular

 <td mat-cell *matCellDef="let row">                                                                            
   <mat-checkbox (click)="$event.stopPropagation()"                                                                                
     (change)="$event ? selection.toggle(row) : null;isSomeSelected()"                                                                               
     [checked]="selection.isSelected(row)">                                                                           
 </mat-checkbox></td>

Solution

  • In your .ts define index as a property of RowModel.

    Then you can access it with row.index in template and controller.

    .ts:

    const ELEMENT_DATA: PeriodicElement[] = [
      {position: 1, name: 'item1', index: 0},
      {position: 2, name: 'item2', index: 1},
      {position: 3, name: 'item3', index: 2},
    ];
    

    .html:

    <td mat-cell *matCellDef="let row">                                                                            
      <mat-checkbox (click)="$event.stopPropagation()"                                                                                
                    (change)="$event ? selection.toggle(row) : null;isSomeSelected()"                                                                               
                    [checked]="selection.isSelected(row)">                                                                       
      </mat-checkbox>
      <span>{{row.index}}</span>
    </td>