Mat Sort header 不对数据进行排序

Mat Sort header does not sort data

我已经用尽了所有示例、文档等。我已经使用 angular 表三年了,甚至在应用程序中我也有这个问题,我还有其他表在使用排序时没有问题。我一直在比较它们,但我无法弄清楚两者之间的区别是什么。

  dataSource: MatTableDataSource<IOrder>;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild('mainTable', { static: false }) table: MatTable<IOrder>;

然后,当数据从 store/http 调用等到达时:

          this.dataSource = new MatTableDataSource(orders);
          this.dataSource.sort = this.sort;
          this.ref.detectChanges();
          this.table.renderRows();

在前端:

<table
        matSort
        class="table"
        mat-table
        multiTemplateDataRows
        [dataSource]="dataSource"
        #mainTable
      >

和定义:

        <tr mat-header-row *matHeaderRowDef="activeColumns; sticky: true"></tr>
        <tr
          mat-row
          *matRowDef="let row; columns: activeColumns; let i = index"
        ></tr>

然后是实际行的示例:

<ng-container matColumnDef="UPRN">
          <th
            class="table-header"
            mat-header-cell
            *matHeaderCellDef
            mat-sort-header="UPRN"
          >
            UPRN
          </th>
          <td class="table-cell" mat-cell *matCellDef="let row">
            {{ row.site.UPRN }}
          </td>
        </ng-container>

我也有一个用于 createdAt 的,它是相同的。

一切似乎都已正确定义并且没有任何错误。

如果我登录控制台进行mat排序,我可以在'Entries'中看到所有正确的rows/columns。

如果一切正确, 我认为它不起作用,因为它正在寻找 row.UPRN 而不是 row.site.UPRN 因为你定义了 mat-sort-header="UPRN" 请尝试像这样执行自定义排序逻辑

https://stackblitz.com/edit/angular-1urgk9

希望能帮到您解决问题

实际起作用的是提供一个带有 switchcase 的函数作为 dataSource.sortingDataAccessor 属性 的值,如下所示:

          this.dataSource.sortingDataAccessor = (item, property) => {
            switch (property) {
              case 'UPRN':
                return item.site.UPRN;
              case 'Status':
                return item.status;

              case 'Updated at': {
                return item.updatedAt;
              }
              case 'Updated By': {
                return item.updatedByFriendly;
              }
              case 'Created by': {
                return item.createdByFriendly;
              }
              default: {
                return item[property];
              }
            }
          };

Intellisense 也有助于处理可用的属性。大小写字符串必须与您提供的列定义相同。