我正在使用有角度的材料构建Web应用程序,并试图显示带有排序的表格。排序适用于除此列以外的所有列。这是唯一的变量类型不是字符串或数字的列。
我已经尝试将列def更改为office.name等,但无济于事。
<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>
组件代码:
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();
}
}
答案 0 :(得分:1)
您可以在数据源上使用sortingDataAccessor
对表中的对象进行排序。
假设您的数据源名称为dataSrouce
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource = new MatTableDataSource(yourData);
this.dataSource.sortingDataAccessor = (item, property) => {
switch(property) {
case 'office.name': return item.office.name;
default: return item[property];
}
};
this.dataSource.sort = this.sort
}
然后在您的HTML中,将matColumnDef="office"
更改为matColumnDef="office.name"
<ng-container matColumnDef="office.name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Office </th>
<td mat-cell *matCellDef="let row">{{ row.office.name }}</td>
</ng-container>