I am following the basic example on angular material website. It shows the table with correct data but sorting does not work.
Here is the stackblitz: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts
TS File
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;
}
}
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>