代码之家  ›  专栏  ›  技术社区  ›  Bohao LI

MatSort在Mat Table Angular中工作不正常

  •  2
  • Bohao LI  · 技术社区  · 6 年前

    <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表中,排序只适用于第一列“uid”,而不适用于其他列。

    我从中学到了 link (第一个答案)在 *matcolumndef=“第一个字符串” tree.secondString_ , 第一个字符串 必须等于 第二个字符串 让它发挥作用,但在我的情况下,它 tree.firstString.secondString 我用了两点。

    你知道为什么会发生这样的事情,以及如何使之有效吗?



    请看图片: enter image description here

    当我单击“building uid”列时,将对mat表进行排序,一切工作正常。但是当我单击其他列(地址、邮政编码、城市、国家)时,它只对前两行进行排序,并且只对升序排序起作用(降序排序不起作用),其余的行根本不进行排序。

    2 回复  |  直到 6 年前
        1
  •  2
  •   J. S.    6 年前

    您需要覆盖SortingAccessor:

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

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

        2
  •  0
  •   Bohao LI    6 年前

    在我的例子中,我已经做了以下的工作来让它工作。

    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;
    });