【问题标题】:matSort not working properly in mat-table AngularmatSort 在 mat-table Angular 中无法正常工作
【发布时间】:2018-11-07 19:43:47
【问题描述】:

我的 .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;
  }
  ...
}


但在我的 mat-table 中,排序仅适用于第一列“uid”,不适用于其他列。

我从 link(first answer) 了解到,在 *matColumnDef="firstString"{{tree.secondString}} 中,firstString 必须等于 secondString 才能使其工作,但就我而言,它是 tree.firstString.secondString,我使用了两点。

知道为什么会发生这种情况以及如何使其发挥作用吗?



请看图片:

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

【问题讨论】:

  • 遇到同样的问题here
  • 请提供一个演示您的问题的最小演示。

标签: angular


【解决方案1】:

你需要覆盖sortingAccessor:

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

在这种情况下,数据在 item.data 中而不是 item 中更深一层。

【讨论】:

    【解决方案2】:

    就我而言,我已完成以下操作以使其正常工作。

    this.dataSource.sortingDataAccessor = ((data: any, sortHeaderId: string) => {
      let toReturn: any;
      if (sortHeaderId === 'uid')
        toReturn = data[sortHeaderId];
      else
        toReturn = data.location[sortHeaderId];
      if (typeof toReturn === 'string')
        toReturn = toReturn.toLowerCase();
      return toReturn;
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      相关资源
      最近更新 更多