如何在 material table Angular 中获取行索引

How to get row index in material table Angular

如何在 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>

你可以这样声明索引 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>

在您的 .ts 中将 index 定义为 RowModel 的 属性。

然后您可以在模板和控制器中使用row.index访问它。

.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>