I'm building a web app using angular material and am trying to display a table with sorting. The sorting works on all but this column. This is the only column where the type of the variable isn't a string or a number.
I've already try'd change column def to office.name etc, but to no avail.
<ng-container matColumnDef="office">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Office </th>
<td mat-cell *matCellDef="let row">{{ row.office.name }}</td>
</ng-container>
Component Code:
export class DataTableComponent implements OnInit, OnChanges {
dataTableColumns: string[] = ['name', 'emailAddress', 'office', 'active'];
dataSource: MatTableDataSource<Data>;
data: Data[];
offices: Office[];
value: string;
oldFilterValue: string;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@ViewChild(ContextMenuComponent) public basicMenu: ContextMenuComponent;
@ViewChild(MatTable) table: MatTable<any>;
@ViewChild(MatMenuTrigger)
contextMenu: MatMenuTrigger;
contextMenuPosition = { x: '0px', y: '0px' };
constructor(
private dataService: DataService,
public dialog: MatDialog,
private officeService: OfficeService,
public snackBar: MatSnackBar) {
}
ngOnInit() {
this.getData();
this.getOffices();
}
ngOnChanges(changes: SimpleChanges): void {
this.updateTable();
}
getData(): void {
this.dataService.get().subscribe((res) => {
setTimeout(() => {
this.data= res as any[];
this.updateTable();
});
}
updateTable(): void {
this.dataSource = new MatTableDataSource(this.data);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
if (this.value) {
this.applyFilter(this.value);
}
}
getOffices(): void {
this.officeService.getOffices().subscribe((res) => {
this.offices = res;
});
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
row.office.namethat's why it not work. follow the document: material.angular.io/components/table/overview#sorting