mat-sort-header / mat-sort不适用于来自其他数据库的特定列

Ami*_*wat 0 typescript angular-material angular mat-table

mat-sort无法处理mat-table来自另一个数据库的的一个列,其余的列则工作正常。唯一的区别是,我正在从另一服务获取该列的数据。

我试图解决它,ngAfterViewInit但无济于事。

ngAfterViewInit(){
  this.dataSource.sort = this.sort;
};
Run Code Online (Sandbox Code Playgroud)
<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> Resource </th>
  <td mat-cell *matCellDef="let element"> {{element.creator.name}} </td>
  <td mat-footer-cell *matFooterCellDef> </td>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
displayedColumns: string[] = ['projectName', 'date', 'hours', 'description', 'name', 'location', 'Edit'];

@ViewChild(MatSort) sort: MatSort;

ngOnInit(){
  this.dataSource.sort = this.sort;
}
Run Code Online (Sandbox Code Playgroud)

Fab*_*üng 5

不知道您的数据模型,这样的事情应该可以解决您的问题(在您的中ngOnInit):

this.dataSource.sortingDataAccessor = (item, property) => {
  if (property === 'name') {
    return item.creator.name;
  } else {
    return item[property];
  }
};
Run Code Online (Sandbox Code Playgroud)

排序不适用于此字段,因为Angular尝试通过字符串ID访问该列数据,该列ID为name,但该列数据实际上位于element.creator.name(Angular在下面element.name)。

有关更多信息,请在此处(完整显示在页面底部)查看完整的文档,其中注明:

数据访问器函数,用于访问数据属性以通过默认sortData函数进行排序。此默认功能假定排序标题ID(默认为列名)与数据的属性匹配(例如,列Xyz表示data ['Xyz'])。可以将其设置为针对不同行为的自定义函数。


KEV*_*HAL 5

如果您的字段之一mat-table不起作用,那么您需要displayedColumns使用 HTML 代码检查您的matColumnDef

如果该剂量不匹配,则您需要将其作为双方tshtml双方共同使用。

例如:displayedColumns在 TS 端有 NAME、TAGSCREENS,在 HTML 端你给了一些其他的名字,然后排序标题不起作用,如果让它通用,那么它对你有用。

displayedColumns: string[] = ['name', 'tagScreens'];
dataSource= new MatTableDataSource([]);
Run Code Online (Sandbox Code Playgroud)

您需要导入这些MatSort组件

@ViewChild(MatSort, { static: true }) sort: MatSort;
Run Code Online (Sandbox Code Playgroud)
<ng-container matColumnDef="name">
     <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
     <mat-cell *matCellDef="let element">{{element.name}} </mat-cell>
</ng-container>

 <ng-container matColumnDef="tagScreens">
     <mat-header-cell *matHeaderCellDef mat-sort-header> Screens </mat-header-cell>
     <mat-cell *matCellDef="let element">
            {{ element.tagScreens.length > 0 ? (element.tagScreens | separateWithComa : seprateWithCommaPipeConst.name) : 'NA'}}
      </mat-cell>
 </ng-container>
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请单击此处