AppDividend
Latest Code Tutorials

Angular Material Table Example | Angular 8 Filter, Sorting

6

Angular Material Table Example is today’s leading topic.  We use Angular 8 and Angular Material for this demo example.  Angular Material is the ground running with significant, modern UI components that work across the web, mobile, and desktop applications. 

Angular Material components will help us to construct attractive UI and UX, consistent, and functional web pages and web applications while keeping the modern web design principles like browser portability and compatibility. In today’s post, we will use the table component in the Angular Material library. So let us start an Angular 8 Material Table Example From Scratch.

Angular Material Table

Content Overview

First, install an Angular 8. We are using Angular CLI version 8 to install the Angular. Right now, Angular 8 is the latest version. So if you have not installed Angular CLI, then install it using the following command. It will install the Angular CLI 8 because right now, it is the latest version, and from that, you will install Angular 8.

#Step 1: Install Angular 8

Type the following command.

npm install -g @angular/cli

If you are using Mac, then prepend sudo command to get the admin privilege, and if you are a windows user, then please open the CMD in Administrator mode, and you can install the above package globally on your machine.

Now, generate the Angular 8 project using the following command.

ng new mat8table

#Step 2: Install Angular Material Libraries.

Go inside the project folder and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is an optional dependency and helps with touch support for the few of the components.

Now, install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Now, include hammerjs inside an angular.json file. You can find this file on the root of the angular project.

"scripts": [
     "./node_modules/hammerjs/hammer.min.js"
]

#Step 3: Create the Custom Material Module File.

Okay, now inside the src >> app folder, create one module file called material.module.ts. We have created this material.module.ts. file separate because in the future, we can import the different Material components in this file, and this file we will import inside the app.module.ts file.

Write the following code inside the material.module.ts file.

// material.module.ts

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

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

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

export class MaterialModule {}

Here, we have imported the only MatTableModule component from the Angular Material Library.

#Step 4: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes provide us with set off the colors and basic styling. The main available themes are these: indigo-pinkdeeppurple-amberpurple-green, and pink-bluegrey. To import the theme in our project, we can add the following code to your global styles.css file. The file is inside the src folder.

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

You can also have access to the Material Design icons and use these named icons with the <mat-icon> component. To import them to your project, you can add this to the head section of your project’s root index.html file.

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Now the final step is to import material.module.ts and other angular material modules and BrowserAnimationsModule files inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

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

#Step 5: MatTableModule Explanation

The mat-table provides the 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.

Let us take an example of documentation. Now, write the following code inside the app.component.ts file.

// app.component.ts

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

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'},
];

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})
export class AppComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

Here, we have defined the PeriodicElement interface with the four variables. It is a model that has its properties with the datatypes.

Then we have defined the sample data, and inside the AppComponent class, we have defined the displayedColumns array, which consists of column names.

Inside the app.component.css file, we can write the CSS code.

table {
  width: 100%;
}

Finally, write the HTML code inside the app.component.html file.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

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

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

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

  <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>

The mat-table element transforms this table into a material one.

With the dataSource attribute, we provide a data source for our table. Inside every ng-container tag, we define the column definition and the value to be displayed. 

Finally, in the last two tr tags, we define an order for our header columns and the row definitions. So, what we need to do right now is to create our datasource and displayedColumns properties in the app.component.ts file.

Save a file and start the development server.

ng serve -o

Angular Material Table Tutorial

If all of your configurations are right, then you can able to see the table on your homepage.

If we change the order of elements inside the displayedColumns array, it will change the order of the columns inside our table.

Right now, if we start our application then on the home page, we are going to see a populated material table.

#Step 6: Angular Table Pagination

We can also add the pagination to our Angular Table. For that, we need to configure the Table. First, we need to import MatPaginatorModule. So, import the MatPaginatorModule inside the material.module.ts file.

// material.module.ts

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 MaterialModule {}

Now, we need to import the MatPaginator and MatTableDataSource inside the app.component.ts file.

// app.component.ts

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

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'},
  {position: 11, name: 'Soldium', weight: 1.0079, symbol: 'Na'},
  {position: 12, name: 'Magnesium', weight: 4.0026, symbol: 'Mg'},
  {position: 13, name: 'Aluminium', weight: 6.941, symbol: 'Al'},
  {position: 14, name: 'Silicon', weight: 9.0122, symbol: 'Si'},
  {position: 15, name: 'Phosphorous', weight: 10.811, symbol: 'P'},
];

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

  @ViewChild(MatPaginator) paginator: MatPaginator;

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

Here, we have passed our static array data to the MatTableDataSource, and then we have assigned that data to the paginator object so that we can display the data according to pagination value.

Now, finally, add the Paginator element inside the app.component.html file.

<div>
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>
  
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>
  
    <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>
  <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
</div>

Save the file and go to the http://localhost:4200/.

Angular Material Table Pagination Example

Here, you can see we have passed the pageSizeOptions property as an array and also pass the showFirstLastButtons options.

#Step 7: Angular Material Table Sorting

We want to add the sorting functionality to our table, and for that purpose, we are going to use the matSort directive on the table tag.

Moreover, we need to place the mat-sort-header directive for each header cell that will trigger sorting.

First of all, we need to import the MatSortModule inside the material.module.ts file. Write the following code inside the material.module.ts file.

// material.module.ts

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 {}

Also, add the CSS code inside the app.component.css file.

table {
  width: 100%;
}
th.mat-sort-header-sorted {
  color: black;
}

Now, import the MatSort module inside the app.component.ts file.

// app.component.ts

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

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'},
  {position: 11, name: 'Soldium', weight: 1.0079, symbol: 'Na'},
  {position: 12, name: 'Magnesium', weight: 4.0026, symbol: 'Mg'},
  {position: 13, name: 'Aluminium', weight: 6.941, symbol: 'Al'},
  {position: 14, name: 'Silicon', weight: 9.0122, symbol: 'Si'},
  {position: 15, name: 'Phosphorous', weight: 10.811, symbol: 'P'},
];

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  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;
  }
}

By default, sorting starts with ascending order first and then descending. We can change that behavior by adding the matSortStart attribute to desc next to the matSort directive.

If we don’t want to use MatTableDataSource for sorting, but to provide our own sorting logic, we can use the (matSortChange) event to receive the active sorting column and the sorting order as well.

Same as the paginator object, we have attached the sort object to the dataSource. Now, we all need to do is add the properties inside the app.component.html file.

<div>
  <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>
  <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
</div>

Save the file, and now you have working Angular Material Table with Pagination and Sorting.

#Step 8: Angular Material Filtering Functionality

For this functionality, we need to provide our own input field and a custom function to filter our data. Only then, we can use MatTableDataSource’s filter property. To implement filtering, we are going to add the following code right above our table in the app.component.html file.

<div fxLayout fxLayoutAlign="center center">
  <mat-form-field fxFlex="40%">
    <input matInput type="text" (keyup)="doFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>
</div>

 And then to write the following function in the app.component.ts file.

// app.component.ts

public doFilter = (value: string) => {
    this.dataSource.filter = value.trim().toLocaleLowerCase();
  }

Finally, because we are using the matInput directive to transform regular input into the material input field, we need to register its modules inside the material.module.ts file.

// material.module.ts

import { ..., MatFormFieldModule, MatInputModule } from '@angular/material';

imports: [
    MatFormFieldModule,
    MatInputModule,

exports: [
    MatFormFieldModule,
    MatInputModule,

As we can see from the HTML file, we are using the fxLayout directive,

Now, we need to import FlexLayoutModule into the app.module.ts file as well:

// app.module.ts

import { FlexLayoutModule } from '@angular/flex-layout';
imports: [
    ...
    FlexLayoutModule
  ],

Now, we have fully completed the Angular 8 Material Table with Filtering, Sorting, Pagination functionality from scratch.

Finally, Angular Material Table Example | Angular 8 Filter, Sorting, Paging Tutorial is over.

People also search

Angular Material Example Tutorial

Angular Modal Tutorial

Angular Material Icon Tutorial

Angular NgClass Example

Angular Forms Tutorial

6 Comments
  1. dhamodar says

    Awsome work bro keep it up

  2. Bertsu says

    Wonderful explanation! Keep up the good work!

  3. Indira says

    Excelents results. All works fine. Thk

  4. Blessing says

    Great article thanks from Zimbabwe

    1. Webster says

      Kwese Uko

  5. Dave says

    Many great tutorials pm mat-table. Thanks for this one. I wish it supported the ability to display rows vertically
    as in:
    fieldName: value
    fieldName: value
    fieldName: value
    fieldName: value
    ….

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.