I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected.
For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts
Below is how the TS file looks:
export class TableSortingExample implements OnInit, AfterViewInit {
ELEMENT_DATA: any;
dataSource: MatTableDataSource<any>;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.ELEMENT_DATA = {
customerHeader: ["ID", "Name", "Address"],
customerDataRows: [
["1", "Mark", "10"],
["2", "John", "110"],
["3", "John", "110"]
]
};
this.dataSource = new MatTableDataSource(
this.ELEMENT_DATA.customerDataRows
);
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
}
And here's a snippet of the HTML file:
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container
*ngFor="let custColumn of ELEMENT_DATA.customerHeader; let colIndex = index"
matColumnDef="{{ custColumn }}"
>
<mat-header-cell *matHeaderCellDef mat-sort-header
>{{ custColumn }}</mat-header-cell
>
<mat-cell *matCellDef="let customerRow">
{{customerRow[colIndex]}}
</mat-cell>
</ng-container>
<mat-header-row
*matHeaderRowDef="ELEMENT_DATA.customerHeader; "
></mat-header-row>
<mat-row *matRowDef="let row; columns: ELEMENT_DATA.customerHeader"></mat-row>
</table>