材料角表不排序包含对象的列



我正在使用Angular材料构建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();
    }
  }

您可以在数据源上使用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>

最新更新