matSort is an Angular Material directive applied to a table to provide sorting behavior. Pair it with mat-sort-header on sortable header cells, then connect the directive to a MatTableDataSource. section 28.2.2
Use matSort as part of the Angular Material table setup:
- Import MatSortModule alongside MatTableModule and the animation support used by the table features. section 28.2.2
- Add matSort to the table element and mat-sort-header to each header that users can sort. section 28.2.2
- Assign the MatSort instance to the data source after child views are available, typically in ngAfterViewInit. section 28.2.2
Sorting a price column
Declare the table with matSort and mark the Price header with mat-sort-header. Clicking that header sorts the Product data when the table uses a connected MatTableDataSource<Product>. 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>
Browse the enhanced table template showing matSort on the table and mat-sort-header on the Price header. section 28.2.2
