为什么 mat-sort-header 在这种情况下不起作用?

Why is mat-sort-header not working in this case?

我正在努力显示 table,并使用 angular material 进行排序。我能够获取列的排序数据:'customer name' 和 'Validity Date' 但 列='Route' 未排序。这是我的代码, 在 html:

   <table mat-table [dataSource]="dataSource" matSort class="width100">
         <ng-container matColumnDef="customerName">
             <th mat-header-cell mat-sort-header *matHeaderCellDef> Customer Name </th>
             <td mat-cell *matCellDef="let element"> {{element.customerName}} </td>
         </ng-container>
         <ng-container matColumnDef="validityDate">
              <th *matHeaderCellDef mat-sort-header mat-header-cell> Validity Date </th>
              <td mat-cell *matCellDef="let element"> {{element.dateOfValidity | date: 'dd-MMM-yyyy'}} </td>
         </ng-container>
         <ng-container matColumnDef="route">
              <th *matHeaderCellDef mat-sort-header mat-header-cell> Route </th>
              <td mat-cell *matCellDef="let row"> {{row.oPortCountryCode}}, {{row.oPortCode}} >>
                        {{row.dPortCountryCode}}, {{row.dPortCode}}</td>
         </ng-container> 
   </table>

在 .ts 文件中:

public dataSource: MatTableDataSource<QuotationModel>;
ngOnInit() {
this.service.getList().subscribe(resp => {
 this.dataSource = new MatTableDataSource<QuotationModel>(resp.items);
            this.dataSource.sort = this.sort;
            this.dataSource.sortingDataAccessor = (item, property) => {
                switch (property) {
                    case 'validityDate':
                        const newDate = new Date(item.dateOfValidity);
                        return newDate;
                    default:
                    return item[property];
                }
            }; 
});
}

模型是:

export interface QuotationModel{
customerName: string;
dateOfValidity: Date;
oPortCountryCode: string;
oPortCode:string;
dPortCountryCode:string;
dPortCode:string;
}

在您的情况下,排序访问器将尝试按 属性 route 排序,因为它是您的 matColumnDef。向您的排序访问器添加一个案例,它 returns 与您显示的值相同,它将按此列的字母顺序排序。

ngOnInit() {
  this.service.getList().subscribe(resp => {
    this.dataSource = new MatTableDataSource<QuotationModel>(resp.items);
    this.dataSource.sort = this.sort;
    this.dataSource.sortingDataAccessor = (item, property) => {
      switch (property) {
        case 'validityDate':
          const newDate = new Date(item.dateOfValidity);
          return newDate;
        case 'route':
          return item.oPortCountryCode + ", " + item.oPortCode + " >> " + item.dPortCountryCode + ", " + item.dPortCode;
        default:
          return item[property];
      }
    }; 
  });
}