Friday 21 September 2018

Adding Paginator to Angular Material Table

To add paging feature of pre-fetched data to Angular Material 6 Table:
- on html page add mat-paginator to the bottom (or top) of the table:
<mat-paginator [pageSizeOptions]="[2, 5, 10]"></mat-paginator>

- on module page (e.g., module.ts):
//import MatPaginatorModule
import { MatPaginatorModule } from '@angular/material/paginator';
@NgModule({
  . . .,
  imports: [
    . . .
    MatPaginatorModule
  ],
. . .
})

- on component page (e.g., component.ts):
// import ViewChild, MatPaginator and MatTableDataSource
import { ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';

export class AppComponent implements AfterViewInit, OnInit{

  . . .

  dataSource : MatTableDataSource<MyDataModel>;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngAfterViewInit() {
    // set datasource paginator
    this.dataSource.paginator = this.paginator;
  }

  ngOnInit() {
    // initialise the datasource
    this.dataSource = new MatTableDataSource<MyDataModel>(MY_DATA);
  }
}

I will create a post of how to do paging and sorting with server-side data interaction soon.


No comments: