3

I have used a mat-table in my Angular7 app with firebase and have populated it successfully. I want to add an auto incrementing serial no.

My Html for the code:

<mat-table #table2 [dataSource]="dataSource2" matSort>
 <ng-container matColumnDef="sn">
 <mat-header-cell *matHeaderCellDef mat-sort-header> SN. </mat-header-cell>
 <mat-cell *matCellDef="let element; let i = index;">{{i+1}}</mat-cell>
  </ng-container>
 <ng-container matColumnDef="description">
 <mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
    <mat-cell *matCellDef="let item"> {{item.description}} </mat-cell>
  </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" [pageSize]="5" showFirstLastButtons></mat-paginator>

Issue with pagination

  • When I go to the next page, the index starts again from one.
  • If I am showing 5 item per page then after goes to next page it starts with one instead of 6.
Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
Supritha
  • 79
  • 2
  • 12

1 Answers1

7

To get the index to update for the next pages... we do the following:

( [pageIndex] X [pageSize] ) + ( [rowIndex] + 1 )... which comes down to the following in our code:

<mat-table #table2 [dataSource]="dataSource2" matSort>
 <ng-container matColumnDef="description">
 <mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
    <mat-cell *matCellDef="let item; let j = index"> 
      {{ (j+1) + (myPaginator.pageIndex * myPaginator.pageSize) }} - 
      {{item.description}} </mat-cell>
  </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #myPaginator [length]="25"
              [pageSize]="5"
              [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator> 

you can check working stackblitz demo here

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70