Please try the below.
If you want to change the default direction, change it on the ngOnInit method call to this.sortItem
// app.component.ts
import { Component, ViewChild } from '@angular/core';
import { Sort, MatSort, MatPaginator } from '@angular/material';
import { interval } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public displayedColumns: string[] = ['name', 'break',];
public sortedData: any;
constructor( ) { }
ngOnInit() {
setTimeout(() => {
this.sortItem({ active: 'break', direction: 'asc' });
}, 1000);
}
compare(a: number | string, b: number | string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
sortItem(sort: Sort) {
const data = DATA_SOURCE.slice();
if (!sort.active || sort.direction === '') {
this.sortedData = data;
return;
}
this.sortedData = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'break': return this.compare(a.breakTime.start, b.breakTime.start, isAsc);
default: return 0;
}
});
}
}
const DATA_SOURCE = [
{
name: 'Alice',
breakTime: {
start: '14-00',
end: '14-00'
},
},
{
name: 'Steve',
breakTime: {
start: '10-00',
end: '11-00'
},
},
{
name: 'Bob',
breakTime: {
start: '12-00',
end: '13-00'
},
},
];
// app.component.html
<table mat-table [dataSource]="sortedData" multiTemplateDataRows
matSort (matSortChange)="sortItem($event)"
class="mat-elevation-z4 w-100">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let item"> {{item.name}} </td>
</ng-container>
<ng-container matColumnDef="break">
<th mat-header-cell *matHeaderCellDef mat-sort-header > Break </th>
<td mat-cell *matCellDef="let element">
{{element.breakTime.start}} - {{element.breakTime.end}}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let element; columns: displayedColumns;"
class="element-row"
[class.example-expanded-row]="expandedElement === element"
(click)="expandedElement = expandedElement === element ? null : element">
</tr>
</table>