angular - matSort 在 mat-table Angular 中无法正常工作

标签 angular

我的 .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 (第一个答案)在 *matColumnDef="firstString"{{tree.secondString}} 中,firstString 必须等于 secondString 使其工作,但就我而言,它是 tree.firstString.secondString,我使用了两个点。

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



请看图片: enter image description here

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

最佳答案

您需要覆盖 sortingAccessor:

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

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

关于angular - matSort 在 mat-table Angular 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50579494/

相关文章:

angular - 在索引 html Angular 2 中加载文本

javascript - 如何在多个 Angular 2 项目之间共享一个 Angular 2 组件?

angular - 为什么 `combineLatest` 返回 OperatorFunction<{}, number>

angular - md-tabs 使用代码转到 Angular 2 Material 设计中的选项卡

文档中的 Angular FireStore 集合

javascript - 根据条件禁用(点击)功能

javascript - 在错误超时之前重新发送 HTTP post

javascript - 如何使scrollIntoView()在第一次点击时起作用(Angular 6)?

javascript - Angular 2 和原生 Promise

Angular 2 无法绑定(bind)到 'dragula',因为它不是 'div' 的已知属性