how to define index in angular material table

后端 未结 5 865
栀梦
栀梦 2020-12-01 10:16

how should I define an index variable when angular material table is used as ngFor is not used in this table.

I did search for it in the documentation but index is

相关标签:
5条回答
  • 2020-12-01 10:36

    For those who are facing problem with keeping the right index when using pagination which table has more than 1 page. It can be especially important when you have editable element, thus you're using a routerLink to add/edit/delete selected elements.

    <ng-container matColumnDef="title">
     <mat-header-cell *matHeaderCellDef mat-sort-header>Title</mat-header-cell>
     <mat-cell *matCellDef="let book; let i = index;" fxLayoutAlign.lt-md="center center">
      <button mat-button [routerLink]="[i + (paginator.pageIndex * paginator.pageSize)]" routerLinkActive="active"</button>
     </mat-cell>
    </ng-container>
    

    As well as

    <mat-paginator #paginator [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
    

    In essence, i + (paginator.pageIndex * paginator.pageSize) is the solution, but it counts from 0. If you'd like to index from 1, simply make it (i+1) + (paginator.pageIndex * paginator.pageSize). Worth to note is that you really need the #paginator and [pageSize]="VALUE".

    0 讨论(0)
  • 2020-12-01 10:43

    Can you add index to let element; let i = index;" as you'd do with *ngFor?

    <mat-row *matRowDef="let row; columns: displayedColumns; let i = index"></mat-row>
    

    Or like so:

    <ng-container matColumnDef="index">
      <mat-header-cell *matHeaderCellDef> Index </mat-header-cell>
      <mat-cell *matCellDef="let element; let i = index;">{{i}}</mat-cell>
    </ng-container>
    
    0 讨论(0)
  • 2020-12-01 10:44

    From Angular 5 you can alias index to local variable i using index as i

    <ng-container matColumnDef="rowIndex">
      <mat-header-cell *matHeaderCellDef> Index </mat-header-cell>
      <mat-cell *matCellDef="let element;index as i;"> {{ i }} </mat-cell>
    </ng-container>
    
    0 讨论(0)
  • 2020-12-01 10:48

    For anyone who has set the multiTemplateDataRows property of mat-table to true, you can't use index. Instead you have use either dataIndex or renderIndex.

    <mat-cell *matCellDef="let row; let i = dataIndex;">{{i}}</mat-cell>
    

    See https://github.com/angular/material2/issues/12793

    0 讨论(0)
  • 2020-12-01 10:56

    If someone using <mat-paginator ../>, then index can be interpreted as below

    <mat-cell *matCellDef="let element; index as i"> {{paginator.pageSize * paginator.pageIndex + i + 1}}</mat-cell>
    
    0 讨论(0)
提交回复
热议问题