2

I am trying to sort a table by its columns. The problem occurs when I have to filter a result that is inside another.

I tried to access the property by bracket notation and dot notation but none gave results. Also placing the final node in matColumnDef but it fails because there are 2 columns with the same name.

<table mat-table [dataSource]="dataSource" matSort>

  <!-- Element name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Username Column -->
  <ng-container matColumnDef="user.name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Username </th>
    <td mat-cell *matCellDef="let element"> {{element.user.name}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

</table>

displayedColumns definition:

displayedColumns = ['name', 'user.name'];

There is a dataSource example:

[
    {
        id: 2,
        name: "Testing",
        user: {
            id: 1, 
            name: "User Testing", 
            username: "test@example.com"
        }
    },
    {
        id: 4,
        name: "Testing_2",
        user: {
            id: 3, 
            name: "User Testing 2", 
            username: "test2@example.com"
        }
    }
]
Leandro Matilla
  • 911
  • 4
  • 14
  • I think this could be the solution https://github.com/angular/components/issues/5927#issuecomment-317016960 – Leandro Matilla Jul 24 '19 at 14:10
  • 1
    I think you are in troubles buddy, check how the value is retrieved https://github.com/angular/components/blob/e4f710a4153060c80f783ece7c080150c16033df/src/material/table/table-data-source.ts#L113 – Lautaro Cozzani Jul 24 '19 at 14:35

1 Answers1

4

It was hard to find documentation on this, but it is possible by customizing the sortingDataAccessor of MatTableDataSource and a switch statement.

For example:

@ViewChild(MatSort) sort: MatSort;

ngOnInit() {
  this.dataSource = new MatTableDataSource(yourData);
  this.dataSource.sortingDataAccessor = (item, property) => {
    switch(property) {
      case 'project.name': return item.project.name;
      default: return item[property];
    }
  };
  this.dataSource.sort = sort;
}

Found here: Angular Material 2 DataTable Sorting with nested objects

hc_dev
  • 8,389
  • 1
  • 26
  • 38
cesar moro
  • 168
  • 8
  • There is also a tutorial explaining custom sorting: [Angular mat-table sort example: Adding sorting to the material table](https://www.angularjswiki.com/material/mat-table-sort/) – hc_dev Jul 01 '22 at 11:15