Implementing a Minimal Angular Material Data Table With Sorting | Task

Ole Ersoy
Mar - 01  -  2 min

Scenario

Building on our previous minimal data table adding sorting:

Approach

Imports

import { MatSortModule } from '@angular/material/sort';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { ViewChild, AfterViewInit } from '@angular/core';

Add MatSortModule and BrowserAnimationsModule to app.module.ts.

Templating

Add the matSort and mat-sort-header directives:

<mat-table class="mat-elevation-z8" [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let row;">{{row.id}}</mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns">
    </mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

DataSource

First grab the template sort directive element with the @ViewChild annotation:

@ViewChild(MatSort, {static: false}) sort: MatSort;

Then configure the data source like this:

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

We have implemented the AfterViewInit interface like this:

export class AppComponent implements OnInit, AfterViewInit {...}

Demo