'How do I sort a material table with favorites on top?

I wanted to sort a mat-table (or MatTable for the search engine) in Angular with the "favorite" items on top.

I want the favorite items to always be the first items of the table no matter what sorting is currently set.

I looked up the internet but nothing found so I had to do it myself.



Solution 1:[1]

This is my solution: https://stackblitz.com/edit/angular-defaultsort-zgwgpv

Here are the main parts of the implementation.

Redirecting the sorting into a method called sortData. Here I can sort the data as I like:

<table
  matSort
  (matSortChange)="sortData($event)"
  matSortActive="carbs"
  matSortDirection="asc"
>

This method handles the sort variable and calls the method sortIt:

sortData(sort: Sort) {
  const data = this.desserts.slice();
  if (!sort.active || sort.direction === '') {
    // initially
    this.sortIt('', true, data);
    return;
  }

  this.sortIt(sort.active, sort.direction === 'asc', data);
}

The sortIt method sorts and calls the comparators that are needed. Main thing is, that I check 3 different statuses: both items are favorites (sorting in the "top" favorite part), only one item is favorite (in this case the favorite is "before" the "normal" one), third is when both items are "normal" items, in this case I sort by the different properties.

sortIt(property: string, isAsc: boolean, data: Dessert[]): void {
  this.sortedData = data.sort((a, b) => {
    if (FAVORITES_FIRST) {
      if (a.favorite && b.favorite) {
        return this.sortByBothFavorites(property, isAsc, a, b);
      }
      // if only one favorite, the favorite is on top, no matter asc or desc
      if (a.favorite === true) {
        return -1;
      } else if (b.favorite === true) {
        return 1;
      }
    }

    // if no favorite, standard sorting
    return this.stdSort(property, isAsc, a, b);
  });
}

That's the trick! Have fun with it!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Janos Vinceller