Search code examples
angularhtml-tablepaginator

Paginator changes index of datasource


The sequence number of this table is determined by the index number of the array:

<table mat-table [dataSource]="dataSource" class="table" aria-describedby="reviewScheduleTableDesc"
              id="table">
   <caption class="cdk-visually-hidden" id="reviewScheduleTableDesc">Review Schedule  Table</caption>
              <ng-container matColumnDef="sequence">
     <th mat-header-cell *matHeaderCellDef class="table-header-cell" scope="col"> Sequence  </th>
                <td mat-cell *matCellDef="let element; let i = index"
                  matTooltip="{{ i+1 }}"> {{ i+1 }} </td>
       </ng-container>`

and this is the code for the paginator:

<div class="paginator" *ngIf="this.reviewScheduleData.length > 3">
<mat-divider></mat-divider>
<div class="custom-paginator details-custom-paginator">
<mat-paginator [pageSizeOptions]="[3]" [pageSize]="3"></mat-paginator>
</div>
</div>

in ts file:

@ViewChild(MatPaginator) set matPaginator(paginatorValue: MatPaginator) 
 {
   if (paginatorValue !== undefined && this.dataSource) {
    this.paginator = paginatorValue;
    this.dataSource.paginator = paginatorValue;
 }
}

When there is no paginator, all 8 items show as expected with the appropriate sequence number. However, when there is the paginator, and it is on the 2nd pageindex, the sequence number is the same (index + 1) as the index of the array the paginator.

So the sequence numbers will 1,2 and 3 instead of 4,5 and 6 on the 2nd pageindex and that is incorrect.

When I do not assign a paginator

When I have a paginator and set to 3 items per page

How can I get the sequence number to 4,5, and 6 on the second page in the paginator?

I tried to assign a variable to the pageindex so I calculate it to show the right sequence number. For example, {{ i+1 + 3 * this.pageIndex}}. But I am not able to assign the pageindex to a variable.


Solution

  • Use a template reference variable to the paginator and use some like

    <table mat-table [dataSource]="dataSource" ...>
        <ng-container matColumnDef="sequence">
           <th mat-header-cell *matHeaderCellDef class="table-header-cell" scope="col"> Sequence  </th>
           <td mat-cell *matCellDef="let element;let i=index"> 
                {{i+1+(paginator?paginator.pageSize*paginator.pageIndex:0)}}
           </td>
        </ng-container>
        ....
    </table>
        <!--see the templater variable reference: #paginator-->
        <mat-paginator #paginator [pageSizeOptions]="[5, 10, 20]"
                     showFirstLastButtons
                     aria-label="Select page of periodic elements">
        </mat-paginator>