Angular Material Data Table Pagination

In this lecture let's take a look at pagination in data tables, similarly to sorting pagination can be implemented in three simple steps.

1st Step: Import the MatPaginatorModule

For that let's open material.module.ts import MatPaginatorModule and add it to the MaterialComponents[] array.

import { MatPaginatorModule } from "@angular/material";

const MaterialComponents = [
  MatPaginatorModule,
]

2nd Step: Add Paginator component in the HTML

So after <mat-table> add <mat-paginator> and specify two options to the paginator, the first one is the page size using pageSizeOptions let's go with [5, 10, 20] the second option is to show the first and last buttons of the paginator using showFirstLastButtons as an attribute.

    ....
    </mat-table>
    <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons></mat-paginator>

3rd Step: Provide the MatPaginator directive

Now we need to provide the MatPaginator directive to the dataSource, so in the typscript file import MatPaginator from @angular/material and then use the ViewChild decorator to get hold of a reference to the MatPaginator component. Finally in the ngOnInit method we assign the MatPaginator component to the paginator property of the dataSource.

import { Component, ViewChild, OnInit } from "@angular/core";
import { MatSort, MatPaginator } from "@angular/material";
...
export class AppComponent implements OnInit {
   ...
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
  }

}

Let's save the files and take a look at the browser. angular material data table pagination at first glance you can see that the styling is sort of broken so let's fix that, in the HTML you just need to wrap the <mat-table> and <mat-paginator> in a div tag and the move the mat-elevation-z8 class from <mat-table> to the <div> tag.

<div class="mat-elevation-z8">
  <mat-table [dataSource]="dataSource" matSort> ....
  </mat-table>
  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons>
  </mat-paginator>
</div>

Now if you save the file and take a look at the browser again you can see that it looks much better. angular material data table paginator By default 5 items are displayed per page you can change it to 10 or 20. angular material data table pagination pages You can also go back and forward between pages using the icon buttons.