1
votes

I'm trying to sort table constructed with angular material. Following the example of the documentation: https://v5.material.angular.io/components/table/examples I manage to sort tables by column when column's name matches the data property name.

For example, if my object is: foo.name, when I use:

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'];

It is working fine.

However, if my object structure is different (for example, in my case i found name in foo.propieties.name) I do not find the way to being able to order by name.

I found that:

By default, the MatTableDataSource sorts with the assumption that the sorted column's name matches the data property name that the column displays.

but I didn't find any solution for cases when it is not true

1
You can rename your displayed column to properties.name - Jorge Mussato

1 Answers

4
votes

In 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>

in .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'];