Monday, July 9, 2018

I learned how to add a pagination control to an Angular Materials data table in an Angular 6 application today.

I cleaned up the component I first offered here using this as a guide. The revamp looks like so:

import { Component, OnInit } from '@angular/core';
import { President } from '../models/president.model';
import { PresidentialContract } from '../contracts/presidential.contract';
import { MatTableDataSource, MatPaginator } from '@angular/material';
import { ViewChild } from '@angular/core';
   selector: 'materials-list',
   templateUrl: './materialsList.component.html',
   styleUrls: ['./materialsList.component.css']
export class MaterialsListComponent implements OnInit {
   public presidents:Array<President>;
   private displayedColumns = ["Name", "Party", "HasNonconsecutiveTerms"];
   dataSource: MatTableDataSource<President>;
   @ViewChild(MatPaginator) paginator: MatPaginator;
   ngOnInit(): void{
         function(data) {
            this.presidents = data;
            this.dataSource = new MatTableDataSource<President>(this.presidents);
            this.dataSource.paginator = this.paginator;
   constructor(public presidentialContract : PresidentialContract) {


I had to change up the template too and inadvertently I discovered that a lot of the tags could be reworked. The mat-table tag could become just a table tag with mat-table designation jammed inline within the tag. Other nested tags within the table tag could similarly be revisited and reworked.

<div id="wrapper">
   <table mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
      <ng-container matColumnDef="Name">
         <th mat-header-cell *matHeaderCellDef>Name</th>
         <td mat-cell *matCellDef="let president">{{president.Name}}</td>
      <ng-container matColumnDef="Party">
         <th mat-header-cell *matHeaderCellDef>Party</th>
         <td mat-cell class="description-cell" *matCellDef="let president">{{president.Party}}
      <ng-container matColumnDef="HasNonconsecutiveTerms">
         <th mat-header-cell *matHeaderCellDef>HasNonconsecutiveTerms</th>
         <td mat-cell class="duration-cell" *matCellDef="let president">
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
   <mat-paginator [pageSizeOptions]="[10]" showFirstLastButtons></mat-paginator>


BrowserAnimationsModule and NoopAnimationsModule had to be looped in at a module to make this all work as seen below.

import { BrowserAnimationsModule, NoopAnimationsModule } from
   imports: [


If you put more than one number in the array at the mat-paginator tag you will get a little dropdown list of options. That said, I could not get the dropdown list to work. That is a challenge for another day I suppose.

No comments:

Post a Comment