【问题标题】:mat-table sort not working with object path keymat-table 排序不适用于对象路径键
【发布时间】:2020-05-29 20:10:31
【问题描述】:

我想与 mat-table 一起使用的数据不是平面的 - 有不同对象的层。我可以很好地显示数据,但排序不起作用。这是一个使用元素数据的示例,其中字段位于“foo”对象内的一层。我怎样才能使排序工作?

https://stackblitz.com/edit/angular-b8u3zr?file=src%2Fapp%2Ftable-sorting-example.ts

const ELEMENT_DATA: PeriodicElement[] = [
  {foo: {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}},
  {foo: {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}},
  {foo: {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}},
  ...
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

  <ng-container matColumnDef="foo.position">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.foo.position}} </td>
  </ng-container>

  ...

</table>

【问题讨论】:

    标签: angular sorting mat-table


    【解决方案1】:

    根据docs(查看api标签,搜索排序自定义)

    允许通过覆盖sortingDataAccessor来自定义排序,它 定义如何访问数据属性。还允许过滤 通过覆盖 filterTermAccessor 进行自定义,它定义了如何行 数据转换为字符串以供过滤器匹配。

    这就是你需要的,你需要添加类型为sortData的函数
    sortData: ((data: T[], sort: MatSort) =&gt; T[])

    这是一个例子

      @ViewChild(MatSort, {static: true}) sort: MatSort;
    
      ngOnInit() {
        this.dataSource.sort = this.sort;
        this.dataSource.sortData = this.sortData;
      }
      sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
        if (!sort.active || sort.direction === '') {
          return data;
        }
        return data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        // Add other cases (columns)
        // if you are wondering where is this 'position' coming from, check the html tag for the th below 
        case 'position': return isAsc ? 
        (a.foo.position - b.foo.position > 1 ? 1 : -1)  : 
        (a.foo.position - b.foo.position > 1 ? -1 : 1);
         default: return 0;
      }
    });
    }}
    

    HTML

    <th mat-header-cell *matHeaderCellDef mat-sort-header='position'> No. </th>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2012-08-29
      • 2019-04-05
      • 2019-08-15
      • 2018-05-21
      相关资源
      最近更新 更多