Monday, 24 March 2025

Paging in Angular Material Table

We will see how to add paging in Angular Material table. Angular Material used here is version 19.

First we add MatPaginatorModule in our AppModule:
. . .
import { MatPaginatorModule } from '@angular/material/paginator';

@NgModule({
  . . .
  
  imports: [
    . . .
    MatPaginatorModule
  ],
  
  . . .
})

Then add paginator element on the component page:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 alternate-row-table">
   . . .
</table>
<mat-paginator [length]="totalRecords" [pageSize]="pageSize" [pageSizeOptions]="[5, 25, 50]" (page)="onPageChange($event)">
</mat-paginator>

Modify the component class file as well:
// import MatPaginator and MatTableDataSource
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
. . .

export class SearchComponent implements OnInit {
  // add the MatPaginator component
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  . . .
  // make sure we use MatTableDataSource type for our data
  dataSource = new MatTableDataSource<Student>([]);
  totalRecords = 0;
  pageSize = 5;  
  
  ngOnInit(): void {
     . . .
     // assign the paginator when initialising the component
     this.dataSource.paginator = this.paginator;       
  }
    
  findStudents(pageIndex: number, pageSize: number) {

    this.studentService.findStudents(this.model, pageIndex, pageSize)
      .subscribe({
        next: (response: PaginatedResult<Student>) => {
          this.dataSource.data = response.data;
          this.totalRecords = response.totalRecords;
		  . . .
        }
      });
  }

  // respond to paging event
  onPageChange(event: any) {
    this.findStudents(event.pageIndex, event.pageSize);
  }
}

And this is an example of a new type for paginated result:
export class PaginatedResult<T> {
  data!: T[];
  totalRecords!: number;
}

No comments: