Angular Material 8 Data Table, Pagination & Sorting Tutorial

By Digamber Rawat Last updated on
Angular Material 8 Data Table tutorial is going to be explored in this tutorial today. I will create an Angular 8 app to show Angular Material 8 data table example. Angular Material is a ui library with a wide variety of ui components. Angular Material offers data tables to show the data on frontend. We’ll learn to work with angular material tables from scratch using MatTableModule material design service.

Angular Material Data Table Tutorial Demo

In the first step, We’ll install and set up the Angular 8 basic app with the latest Angular CLI. After that, we’ll install the Angular material 8 ui library. Then we’ll learn to work with Angular data tables and Angular table pagination.

#1 – Install and setup Angular 8 project

Install and setup Angular 8 project to display the angular material data tables. Run the following command.

ng new angular-material8-data-table-tutorial

Answer the questions:

# ? Would you like to add Angular routing? = No
# ? Which stylesheet format would you like to use? = CSS

Go to the Angular 8 project folder.

cd angular-material8-data-table-tutorial

#2 – Install and setup Angular Material 8 ui library

To set up angular material 8 ui library, enter the following command.

ng add @angular/material

Select the Angular material theme from the given options:

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink

❯ Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ] 
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ] 
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]

Choose Hammer.js (Gesture recognition support) and Angular browser animation support.

# Set up HammerJS for gesture recognition? (Y/n) = Y
# ? Set up browser animations for Angular Material? (Y/n) = Y

To import the angular material theme, include the given below code to your src > index.html file.

<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Go to src > styles.css file and add the following code.

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Finally, we’ve installed angular material in angular basic app. You can type the below command in terminal to run the angular project.

ng serve --open

To check out the Angular material 8 documentation please visit here.

#3 – Create Separate Angular Material Module File

For better project manageability we’ll create separate angular material module file. Go to app > angular-material.module.ts file. We can keep various angular material ui components in this file, this file will be imported in app.module.ts file.

import { NgModule } from '@angular/core';
import { MatTableModule } from '@angular/material/table';

@NgModule({
  imports: [
    MatTableModule
  ],
  exports: [
    MatTableModule
  ]
})

export class AngularMaterialModule {}

We have successfully imported the MatTableModule data table component from Angular Material 8 UI library.

Now, go to app.module.ts file and import the AngularMaterialModule.

import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

/* Angular material 8 */
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AngularMaterialModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

#4 – Understand MatTableModule Angular Material Data Table Service

The `mat-table` provides a Material Design styled data-table that can be used to display rows of data.

This table builds on the foundation of the CDK data-table and uses a similar interface for its data input and template, except that its element and attribute selectors will be prefixed with mat- instead of cdk-. For more information on the interface and a detailed look at how the table is implemented, see the guide covering the CDK data-table.

Now to show data in data tables on frontend, please go to app.component.html file and add the following code.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Then, go to src > app > styles.css file and add the following code.

table {
  width: 100%;
}

Then, go to app.component.ts file and add the following code.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})
export class AppComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

/* Static data */ 

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

To show the data in our angular data table tutorial, we’ve declared the 4 variables in the PeriodicElement interface.

In next step, we’ve declared the dummy data outside the AppComponent class and getting the data in datasource variable inside the AppComponent class. Then you can see column names via displayedColumns array.

Run the command to start the angular 8 app.

ng serve

Angular Material 8 Data Table

This will be your output data tables demo.

#5 – How to Implement Angular 8 Table Pagination Easily?

Implementing pagination in Angular data table is not difficult. Firstly, We’ll require to import MatPaginatorModule service in angular-material.module.ts file.

import { NgModule } from '@angular/core';

import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material';

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

export class AngularMaterialModule {}

After that, go to app.component.ts file and import the MatPaginator and MatTableDataSource and ViewChild service.

import { Component, ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})

export class AppComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  @ViewChild(MatPaginator) paginator: MatPaginator;

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

/* Static data */ 
export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

Finally go to app.component.html file and place this pagination directive right after your angular table tag is ending.

<!-- Angular 8 pagination -->
<mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>

If every thing goes right, then you’ll get this output.
Angular 8 Data Table Pagination

#6 – Angular Material 8 Data Sorting in Table

To sort the data in angular material data tables, we require to import the MatSortModule material service within the angular-material.module.ts file.

import { NgModule } from '@angular/core';

import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, MatSortModule } from '@angular/material';

@NgModule({
   imports: [
      MatTableModule,
      MatPaginatorModule,
      MatSortModule
   ],
   exports: [
      MatTableModule,
      MatPaginatorModule,
      MatSortModule
   ]
})

export class MaterialModule { }

Then, go to app.component.ts file and import the MatSort module.

import { Component, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})

export class AppComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

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

/* Static data */ 
export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

In order to sort the data in angular material data tables we have bind the sort object to the dataSource array. Just go to app.component.html file and paste the below code.

<div class="wrapper">
  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <!-- Angular 8 pagination -->
  <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
</div>

Finally, go to styles.css file and include the following code.

table {
  width: 100%;
}

th.mat-sort-header-sorted {
  color: black;
}

We’ve finished working with Angular Material 8 data tables along with Angular Data Sorting and Angular pagination. You can check out the GitHub repo here, thanks for reading.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.