1

i'm trying sort an objects list in a table when i click on a header.

I already tried to sort the list from TypeScript then update the variable binded to the table but the list reappears like it was before sort.

//Set with a list from DB
public items: Items[]

let sort: Item[] = this.items.sort((a, b) => parseInt(a.id) - parseInt(b.id));
    console.log(sort);
    this.items = null;
    this.items = sort;

So, is it possible to use a OrderBy pipe like this :

*ngFor="let item of items | OrderBy:'asc':'propertyName'"

Then change the propertyName programmatically ?

Guillaume
  • 108
  • 10

1 Answers1

1

You should be able to do it your way as well, but you need to have a function to trigger change detection and table re-render rows.

@ViewChild(MatTable) table: MatTable<any>;

then you call

this.table.renderRows()

and depending on your change detection strategy you might need to also call

this.ref.detectChanges()

You must inject the change detector ref in your constructor then:

constructor(private ref: ChangeDetectorRef) {}

But then Angular material has this functionality built in, the documentation for this is quite excellent with quite a few up-to-date examples:

[URL]

Here's an example though, copy pasted from there:

<table matSort (matSortChange)="sortData($event)">
  <tr>
    <th mat-sort-header="name">Dessert (100g)</th>
    <th mat-sort-header="calories">Calories</th>
    <th mat-sort-header="fat">Fat (g)</th>
    <th mat-sort-header="carbs">Carbs (g)</th>
    <th mat-sort-header="protein">Protein (g)</th>
  </tr>

  <tr *ngFor="let dessert of sortedData">
    <td>{{dessert.name}}</td>
    <td>{{dessert.calories}}</td>
    <td>{{dessert.fat}}</td>
    <td>{{dessert.carbs}}</td>
    <td>{{dessert.protein}}</td>
  </tr>
</table>

 sortedData: Dessert[];

  constructor() {
    this.sortedData = this.desserts.slice();
  }

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'calories': return compare(a.calories, b.calories, isAsc);
        case 'fat': return compare(a.fat, b.fat, isAsc);
        case 'carbs': return compare(a.carbs, b.carbs, isAsc);
        case 'protein': return compare(a.protein, b.protein, isAsc);
        default: return 0;
      }
    });
  }
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
SebastianG
  • 8,563
  • 8
  • 47
  • 111