Dear Stackoverflow community,
According to Angular material 2 documentation you can add an mdSort directive to your table:
Sorting
Use the mdSort directive and adds a sorting UI the table's column headers. The sort headers emit events that can be used to trigger an update via the table's data source.
Code : component.html
Using the mdSort directive and the md-sort-headers
<md-table fxFlex="100%" #table [dataSource]="dataSource" mdSort>
<ng-container mdColumnDef="category">
<md-header-cell *mdHeaderCellDef md-sort-header> Category </md-header-cell>
<md-cell (click)="alert(element)" *mdCellDef="let element"> {{element.category}} </md-cell>
</ng-container>
...
...
</md-table>
Code: component.ts
Referencing the sort directive:
@ViewChild(MdSort) sort: MdSort;
Injecting it inside the datasource:
this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
And using it to sort the objects:
getSortedData(): Task[] {
const data = this._exampleDatabase.data.slice();
if (!this._sort.active || this._sort.direction === '') { return data; }
return data.sort((a, b) => {
let propertyA: number|string|boolean = '';
let propertyB: number|string|boolean = '';
switch (this._sort.active) {
case 'category': [propertyA, propertyB] = [a.category, b.category]; break;
case 'task': [propertyA, propertyB] = [a.task, b.task]; break;
case 'favorite': [propertyA, propertyB] = [a.favorite, b.favorite]; break;
}
let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
let valueB = isNaN(+propertyB) ? propertyB : +propertyB;
return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
});
}
Now I want to have another sortable table, and I have created another datasource, database etc.
But how do I differentiate to mdSort directive?