0

I am trying to enable sorting on a mat-table, and I understood that *matColumnDef and the binding element must have the same name.
In my case I need to call a getter on the element.

How can I handle this? Can I define an alias?

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef> NAME </th>
  <td mat-cell *matCellDef="let person"> {{person.getName()}} </td>
</ng-container>

Could I alias person.getName() to name somewhere so it will match matColumnDef ?

EDIT:
I tried something like bellow, but it doesn't work:

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef> NAME </th>
  <td mat-cell *matCellDef="let person; let name = person.getName()"> {{name}} </td>
</ng-container>
codentary
  • 993
  • 1
  • 14
  • 33
  • Sorry, but I don't quite understand what you're trying to achieve. Can you maybe create stackblitz with the problem you're going to solve? – yurzui Nov 25 '19 at 16:10

1 Answers1

1

Sorry to tell you that, but things are gonna get a bit more complicated from now on.

As you've set a custom field, you'll have to explain to angular how to access the real "data" to sort on.

Here is a code sample:

@ViewChild(MatSort) sort: MatSort;

constructor() {
   this.datasource = new MatTableDataSource();
}


ngOnInit() {
  this.datasource.sort = this.sort;

  this.datasource.sortingDataAccessor = (person: Person, field: string) => {
    switch (field) {
      case 'name': return person.getName();
      default: throw new Error('Unknown field used for sorting: ' + field);
    }
  };
}

You should take a look at the documentation => https://material.angular.io/components/table/api#MatTableDataSource

millenion
  • 1,218
  • 12
  • 16
  • Thanks, this sounds good, but I have some another issue that is stopping me to get to the point of testing `sortingDataAccessor`. I raised another question here:https://stackoverflow.com/questions/59050538/angular-mat-table-custom-data-source-undefined-matsort – codentary Nov 26 '19 at 13:52