angularangular-material

Default sorting in Angular Material - Sort header


How can I change Angular Material code below, so that data-table is sorted by 'name' column, ascending order by default. Arrow (indicating current sort direction) must be displayed.

This is what I want to achieve:

enter image description here

Original code:

<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>

I was trying something like this, but it doesn't work (no arrow displayed, not sorted)

<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortStart="asc" matSortDisableClear>

Here's link to Plunker


Solution

  • You're mistaking matSortStart for matSortDirection.

    Try this:

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

    https://stackblitz.com/edit/angular-defaultsort?file=src/app/sort-overview-example.html

    matSortStart can be used to reverse the cycle used when sort (e.g. when the user clicks to sort, it starts at desc instead of asc).

    Edit: Thanks Ben for providing an updated example