The mat-sort-header attribute makes a table header sortable. Apply it to the header cell for a column, and add matSort to the containing Angular Material table. section 28.2.2
A working sorting setup requires:
- Import MatSortModule alongside the table and animation dependencies. section 28.2.2
- Use MatTableDataSource for the displayed data. section 28.2.2
- Associate the MatSort directive with the data source after child queries are available. section 28.2.2
Sortable price header
<table mat-table [dataSource]="DataSource" matSort> ... <th mat-header-cell *matHeaderCellDef mat-sort-header>Price</th> ... </table> Clicking Price sorts the table data by that column. section 28.2.2
Listing 28.13. Enhancing the table in the table.component.html file in the src/app/core folder
<table mat-table [dataSource]="DataSource" matSort>
<mat-text-column name="id"></mat-text-column>
<mat-text-column name="name"></mat-text-column>
<mat-text-column name="category"></mat-text-column>
<ng-container matColumnDef="price">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Price</th>
<td mat-cell *matCellDef="let item">
{{item.price | currency:"USD"}}
</td>
</ng-container>
<ng-container matColumnDef="buttons">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let item">
<button mat-flat-button color="accent"
(click)="deleteProduct(item.id)">
Delete
</button>
<button mat-flat-button color="warn"
[routerLink]="['/form', 'edit', item.id]">
Edit
</button>
</ng-container>
<tr mat-header-row *matHeaderRowDef="colsAndRows"></tr>
<tr mat-row *matRowDef="let row; columns: colsAndRows"></tr>
</table>
<mat-paginator [pageSize]="5" [pageSizeOptions]="[3, 5, 10]">
</mat-paginator>
<div class="p-2 text-center">
<button mat-flat-button color="primary" routerLink="/form/create"
[disabled]="isServer">
Create New Product
</button>
</div>
Inspect the complete table-template change that adds matSort and mat-sort-header. section 28.2.2
