Home > Enterprise >  How to get row index in material table Angular
How to get row index in material table Angular

Time:12-12

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>

CodePudding user response:

You can declare index like this let i = index:

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

CodePudding user response:

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>
  • Related