Sorting

The previous figure constitutes a nice looking table, but it lacks a pretty standard functionality, namely that of sorting. We expect that by clicking the header it will sort into ascending and descending respectively, and that it is able to recognize common data types such as strings and integers, and sort those correctly. The good news is that this is very easy to achieve. We need to do the following to ensure that our table can be sorted:

  1. Import and register the MatSortModule.
  2. Create a ViewChild of type MatSort and assign it to the dataSources sort property.
  3. Add the directive matSortHeader to the headers that should be able to be sorted.

We complete the first step by adding the following code to the root module:

import { MatSortModule } from '@angular/material/sort';
@NgModule({
imports: [MatSortModule]
})

Thereafter, we go into our component and add the MatSort ViewChild and assign it to the sort property, as described previously:

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

@Component({
selector: 'table-demo',
templateUrl: './table.demo.component.html',
styleUrls: ['./table.demo.component.css']
})
export class AppComponent {
@ViewChild(MatSort) sort: MatSort;
jediSource: Array<Jedi>;
tableSource: MatTableDataSource<Jedi>;
displayedColumns: string[];

constructor() {
this.displayedColumns = ['name', 'side'];
this.jediSource = [{
name: 'Yoda',
side: 'Good'
}, {
name: 'Darth',
side: 'Evil'
},
{
name: 'Palpatine',
side: 'Evil'
}];

this.tableSource = new MatTableDataSource<Jedi>(this.jediSource);
}

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

At this point, we need to fix the markup and then sorting should work. The changes we need to make to the markup are to simply apply the matSort directive to the whole table and mat-sort-header to each header that should be possible to sort. The code for the markup is now as follows:

<mat-table #table [dataSource]="tableSource" matSort>
// header 'Name'
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>

// header 'Side'
<ng-container matColumnDef="side">
<mat-header-cell *matHeaderCellDef mat-sort-header> Side </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.side}} </mat-cell>
</ng-container>

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

The UI should now indicate with an arrow by the column Name, the direction in which the data is being sorted, as the following image indicates:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset