【问题标题】:Mat Sort Issue for Numbers and Text Columns数字和文本列的 Mat 排序问题
【发布时间】:2018-09-06 17:48:26
【问题描述】:

我有角度材料数据源。角材料版本是 ^5.0.3 排序工作。但是,对于某些列,它的排序不正确。数字和文本在那里。例如,排序后的结果如“XXX”、“1”、“1tesxt”、“1”、“OPD”、OXD、“12”。

<mat-table #table [dataSource]="dataSource" matSort > 
  <ng-container matColumnDef="model">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Model </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.model}} </mat-cell>
  </ng-container>

感谢您的帮助。

【问题讨论】:

    标签: angular angular-material angular-material-5 angular-cdk


    【解决方案1】:
    this.dataSource.sortingDataAccessor = (item, property) => ['length', 'age'].includes(property) ? +item[property] : item[property];
    

    【讨论】:

      【解决方案2】:

      这是因为标准 sortingDataAccessor 将数字字符串转换为数字,而在 Javascript 中,1 &gt; 'one'1 &lt; 'one' 都计算为 false

      作为一种解决方法,您可以定义自己的 sortingDataAccessor 而不使用演员表:

      ngAfterViewInit() {    
        this.dataSource.sort = this.sort;
        this.dataSource.sortingDataAccessor = (data, attribute) => data[attribute];
      }
      

      解决方法是从 Github issue 复制而来的。

      【讨论】:

        【解决方案3】:

        你需要把那些不是数字的字符取出来,把持有数字字符的字符串转换成数值类型的值。

        您的初始列值:“ID0239”。 取出字符后:'0239'。 将字符串转换为数字后:0239.

        而 0239 是您需要在 sortDataAccessor 函数中返回的值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-28
          • 2018-08-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-23
          • 1970-01-01
          相关资源
          最近更新 更多