首页 > 解决方案 > MatSort 按语言 iso 代码

问题描述

我正在尝试在 mat-table 中对 api 派生数据进行排序,但数据以 ISO 代码的形式发送,我可以使用以下库进行翻译:

https://www.npmjs.com/package/iso-639-1

this.dataSource = new MatTableDataSource(response);
<ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>NAME</mat-header-cell>
        <mat-cell *matCellDef="let element">
            {{ getNameByCode(element.code) }}
        </mat-cell>
</ng-container>

通过这个方法调用,表中显示的名称是正确的,但是dataSource没有改变,所以它是按ISO排序而不是按名称排序。我可以在将名称提交到 dataSource 之前对其进行翻译,但我想避免它,因为 ISO 代码是我稍后用于 PUT 操作的标识符。

关于如何解决这个问题的任何建议?

标签: angulartypescriptangular-materialmat-table

解决方案


在您的响应中添加/替换一个新属性并显示/排序这个

我想你有一些像:

this.dataService.getData().subscribe(response)=>{
    this.dataSource = new MatTableDataSource(response);
}

您可以使用 pipe(map) 来转换响应

this.dataService.getData().pipe(
  //to add a new property "codeFormatted"
  map((res:any[])=>{
     res.forEach(x=>x.codeFormatted=this.getNameByCode(x.code)
     return res;
  })
  //or to replace
  //  map((res:any[])=>{
  //   res.forEach(x=>x.code=this.getNameByCode(x.code)
  //   return res;
  //})
).subscribe(response)=>{
    this.dataSource = new MatTableDataSource(response);
}

推荐阅读