Default sorting in Angular Material - Sort header
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
You can programmatically sort the table by invoking the sort(Sortable)
method of the data source. Assuming you've got a dataSource
component property for the data source:
// to put next to the class fields of the component
@ViewChild(MatSort) sort: MatSort
// to put where you want the sort to be programmatically triggered, for example inside ngOnInit
this.sort.sort(({ id: 'name', start: 'asc'}) as MatSortable);
this.dataSource.sort = this.sort;
@ViewChild(MatSort) sort: MatSort;
this.dataSource.sort = this.sort;
const sortState: Sort = {active: 'name', direction: 'desc'};
this.sort.active = sortState.active;
this.sort.direction = sortState.direction;
this.sort.sortChange.emit(sortState);
should work. demo
And to show sorting direction arrow, add next css (workaround)
th.mat-header-cell .mat-sort-header-container.mat-sort-header-sorted .mat-sort-header-arrow {
opacity: 1 !important;
transform: translateY(0) !important;
}
Update for Material (tested with v7.3):
@ViewChild(MatSort) matSort: MatSort;
private someMethod(): void {
this.matSort.sort({ id: 'columnName', start: 'asc', disableClear: false });
}
This will also update the mat-sort-header
's arrow without any workaround
You can bind mat-table sort properties to you component variable also.
As @Andrew Seguin says:
<table matSort matSortActive="name" matSortDirection="asc">
This is proper way to set default sorting if you know which one is that.
In case that you get sorting from somewhere else (in my case from query string params), you can also do it like this (sorting arrows works perfectly here):
sortDirection: 'name', // this can be changed or filled in any time
sortProperty: 'asc',
<mat-table matSort [matSortActive]="sortProperty" [matSortDirection]="sortDirection">