Is there any way to call a function when I click the button of the mat-paginator of Angular

3.3k views Asked by At

Among the 4 buttons, I want to use one of them as a next page button. How to do this?
This is the paginator HTML

<mat-paginator 
   [pageSize]="2"
   [pageSizeOptions]="[2, 4, 6]" showFirstLastButtons>         
</mat-paginator>

These are the relevant parts of the typescript code

recordsDataTable:any[]=[ ];
recordsData !: MatTableDataSource<any>;

@ViewChild(MatPaginator) paginator!: MatPaginator;

ngAfterViewInit()
{
  
   this.userservice.getRecords()
   .subscribe(
     (x)=>
       { 
        this.recordsDataTable=x.data;
        this.recordsData= new MatTableDataSource(x.data); 
        this.recordsData.paginator = this.paginator;
             
       }
      )

}
2

There are 2 answers

1
hansmaad On

The Paginator component handles the whole pagination logic for you. You don't handle clicks on it's buttons. The component has a page event that you can use to handle page changes.

<mat-paginator [length]="length"
               [pageSize]="pageSize"
               [pageSizeOptions]="pageSizeOptions"
               (page)="yourPageChangeLogic($event)">
</mat-paginator> 
0
a.prakash On

In angular material, Paginator comes with an event > (page)="getPageDetails($event)". This event gives us information about the table.

In component.ts file

getPageDetails(event:any) {
  console.log(event);
}

In component.html file

 <mat-paginator showFirstLastButtons
             [length]="totalDataLength"
             [pageSize]="pageSize"
             [pageSizeOptions]="pageOptions"
             (page)="getPageDetails($event)"></mat-paginator>

Example Link: https://stackblitz.com/edit/angular-pyix6j?file=src/app/table-pagination-example.html