[UNIQUE LINK] I'm working on a simple Angular material data table with sorting.
I've gone ahead and added the MatSortModule, used @ViewChild
in my component class, included the directives, set up the dataSource.sort property, and even see the arrow when hovering over the table, but unfortunately, the data isn't sorting as expected.
Any suggestions or ideas?
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatSort } from "@angular/material";
class Task {
id: string;
description: string;
complete: boolean;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
@ViewChild(MatSort, {static: false}) sort: MatSort;
/**
* Control column ordering and which columns are displayed.
*/
displayedColumns:string[] = ['id'];
dataSource: MatTableDataSource<Task>;
ngOnInit() {
const tasks: Task[] = [
{ id: '123', description: 'Complete me!', complete: false },
{ id: '321', description: 'You Completed me!', complete: true }];
this.dataSource = new MatTableDataSource(tasks);
this.dataSource.sort = this.sort;
}
}
<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>