Implementing a Minimal Angular Material Data Table with Paging
Scenario
Building on our previous minimal data table adding paging:
Modules
Import the MatPaginatorModule
:
import { MatPaginatorModule } from '@angular/material/paginator';
Add the mat-paginator
element below the mat-table
element:
<mat-table></mat-table><mat-paginator [pageSizeOptions]="[1, 2]" [pageSize]="1" showFirstLastButtons></mat-paginator>
DataSource
First grab the template paginator directive with the @ViewChild
and AfterViewInit
directives and import them into the component containing the table like this:
import { ViewChild, AfterViewInit } from '@angular/core';
And place this in the AppComponent
class body:
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
Then configure the data source like this:
ngAfterViewInit() {
...
this.dataSource.paginator = this.paginator;
}
Note that we have implemented the AfterViewInit
interface like this:
export class AppComponent implements OnInit, AfterViewInit {...}
If this.dataSource.sort
is set in ngOnInit
the sort will most likely not work.