Sunday, July 31, 2022

[FIXED] how to scroll to top in material table on paginate change

Issue

I am stuck in an issue where in material table, I click on next button, the scroll stays to bottom , whereas it should scroll to top.

<mat-table class="table-container" fxFlex="100" [dataSource]="allUsersDataSource">
  <ng-container matColumnDef="firstName">
    <mat-header-cell fxFlex="25" *matHeaderCellDef> First Name </mat-header-cell>
    <mat-cell fxFlex="25" *matCellDef="let element"> {{element.first_name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="lastName">
    <mat-header-cell fxFlex="25" *matHeaderCellDef> Last Name </mat-header-cell>
    <mat-cell fxFlex="25" *matCellDef="let element"> {{element.last_name}} </mat-cell>
  </ng-container> 
     
  <mat-header-row *matHeaderRowDef="allUsersColumns; sticky: true"></mat-header-row>
  <mat-row *matRowDef="let row; columns: allUsersColumns;"></mat-row>
</mat-table>

<mat-paginator #allUsersPaginator [pageSizeOptions]="[25,50,100]" (page)="onAllUserPaginateChange($event)"
    [length]="allUserPagination.length" [pageSize]="25" showFirstLastButtons></mat-paginator>

This is the code behind

onAllUserPaginateChange(event: any) {
  window.scroll(0,0);
}

Solution

Here I gave an ID to the table

eg.

<mat-table id ="matTable" class="table-container" 
  [dataSource]="allUsersDataSource">
<mat-table>

and in the paginate method of that table in the typescript file.

onAllUserPaginateChange(event: any) {
  const matTable= document.getElementById('matTable');
  matTable.scrollTop = 0;
}


Answered By - Chetan Birajdar
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.