2
votes

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: "[email protected]"
        }
    },
    {
        id: 4,
        name: "Testing_2",
        user: {
            id: 3, 
            name: "User Testing 2", 
            username: "[email protected]"
        }
    }
]
1
I think this could be the solution github.com/angular/components/issues/…Leandro Matilla
I think you are in troubles buddy, check how the value is retrieved github.com/angular/components/blob/…Lautaro Cozzani
I think this will solve your question: stackoverflow.com/questions/48891174/…cesar moro

1 Answers

3
votes

It was hard to find documentation on this, but it is possible by using sortingDataAccessor 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