matSort在Mat-table Angular中无法正常工作?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (463)

我的.html文件:

<mat-table [dataSource]="dataSource" padding matSort>

  <ng-container matColumnDef="uid">
    <!--<mat-header-cell *matHeaderCellDef mat-sort-header>Building UID</mat-header-cell>-->
    <mat-header-cell *matHeaderCellDef mat-sort-header>
      Building UID
    </mat-header-cell>
    <mat-cell *matCellDef="let tree" padding>{{tree.uid}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="address">
    <mat-header-cell *matHeaderCellDef mat-sort-header>
      Address
    </mat-header-cell>
    <mat-cell *matCellDef="let tree" padding>{{tree.location.address}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="zipCode">
    <mat-header-cell *matHeaderCellDef mat-sort-header>
      Zip code
    </mat-header-cell>
    <mat-cell *matCellDef="let tree" padding>{{tree.location.zipCode}}</mat-cell>
  </ng-container>

  ...

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>

</mat-table>

我的.ts文件:

@Component({
  selector: 'page-buildings',
  templateUrl: 'buildings.html',
})
export class BuildingsPage {
  @ViewChild(MatSort) sort: MatSort;
  ...
  private displayedColumns: string[] = ["uid", "address", "zipCode", "city", "country", "treeDetails"]; // tslint:disable-line
  private dataSource: MatTableDataSource<any>;

  ...
  constructor(...) {

    this.dataSource = new MatTableDataSource(...);
    this.dataSource.sort = this.sort;
  }
  ...
}

如何使它工作?

请看图片:

当我点击“Building UID”栏时,mat-table将被排序,一切正常。但是当我点击其他列(地址,邮政编码,城市,国家)时,它只会对前两行进行排序,只有升序排序有效(降序排序不起作用),而其余行则是根本没有排序。

提问于
用户回答回答于

需要覆盖sortedAccessor:

  this.datasource.sortingDataAccessor = ((item: TableItems, sortHeaderId: string) => {
      return item.data[sortHeaderId];
    });

在这种情况下,数据在item.data中保持一个级别,而不是item。

用户回答回答于
this.dataSource.sortingDataAccessor = ((data: any, sortHeaderId: string) => {
  let toReturn: any;
  if (sortHeaderId === 'uid')
    toReturn = data[sortHeaderId];
  else
    toReturn = data.location[sortHeaderId];
  if (toReturn && toReturn instanceof String)
    toReturn = toReturn.toLowerCase();
  return toReturn;
});

扫码关注云+社区

领取腾讯云代金券