网站搜索

typescript - 当列名称与数据属性名称不匹配时,Angular 按列对表格进行排序


我正在尝试对使用 Angular Material 构建的表格进行排序。按照文档的示例:https://v5.material.angular.io/components/table/examples,当列名与数据属性名匹配时,我能够按列对表格进行排序。

例如,如果我的对象是:foo.name,当我使用:

html:

 <table style="width: 100%;" mat-table [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="name">
       <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
       <td mat-cell *matCellDef="let row"> {{ row.name }} </td>
    </ng-container
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
 </table>

ts:

displayedColumns: Array<string> = ['name'];

它运作良好。

然而,如果我的对象结构不同(例如,在我的情况下我在 foo.propieties.name 中找到了 name),我找不到能够按 name 排序的方法。

我发现:

默认情况下,MatTableDataSource 假设排序的列名称与列显示的数据属性名称匹配来进行排序。

但我没有找到在情况不成立时的任何解决办法

答案#1

在 HTML 中:

 <ng-container matColumnDef="foo.propieties.name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

在 .ts 中

sortingDataAccessor(item, property) { 
     console.log(item);
    if (property.includes('.')) { 
      return property.split('.')
        .reduce((object, key) => object[key], item);
    }
    return item[property];
  }
ngAfterViewInit() {
    this.dataSource.sortingDataAccessor = this.sortingDataAccessor; 
    this.dataSource.sort = this.sort; 
  }

displayedColumns = ['foo.properties.name'];