Implementing a Minimal Angular Material Data Table With Sorting

Updated Version

There is an updated version of this article here:

Scenario

Building on our previous minimal data table adding sorting:

Approach

Modules

Import the MatSortModule :

import { MatSortModule } from '@angular/material/sort';

Templating

Add the matSort and mat-sort-header directives:

DataSource

First grab the template sort directive with the @ViewChild and AfterViewInitdirectives 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(MatSort, {static: false}) sort: MatSort;

Then configure the data source like this:

ngAfterViewInit() {
this.dataSource.sort = this.sort;
}

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.

Demo

Related

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation