I'm in the process of organizing my list-component made with Angular Material.
<div style="width:30%;">
<mat-nav-list matSort (matSortChange)="sortData($event)">
<th mat-sort-header="stuff.name">Name</th>
<mat-list-item *ngFor="let stuff of vehicleDetails">
<button matLine (click)="updateInfo(stuff.id)"> {{ stuff.name }} </button>
<button mat-icon-button id="btn" *ngIf='check(stuff.alarm)' matTooltip="{{stuff.alarm[tooltipIndex(stuff)]?.timestamp}} - {{stuff.alarm[tooltipIndex(stuff)]?.description}}">
<mat-icon>info</mat-icon>
</button>
</mat-list-item>
</mat-nav-list>
</div>
The list content consists of various vehicle names extracted from my vehicleDetails array, which stores information like name and id. Currently, I am working on implementing sorting functionality based on the name property. The functions below are intended to assist me in achieving this goal:
export class VehiclelistComponent implements OnInit, AfterViewChecked
{
vehicleDetails: VehicleDetail[] = [];
sortedVehicleDetails: VehicleDetail[];
sortData(sort: Sort) {
const data = this.vehicleDetails.slice();
if (!sort.active || sort.direction === '') {
this.sortedVehicleDetails = data;
return;
}
this.sortedVehicleDetails = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'name':
return this.compare(a.name, b.name, isAsc);
default:
return 0;
}
});
}
compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
Incorporating ngOnInit and ngAfterViewChecked methods:
ngOnInit() {
// Initialize vehicles
this.getVehicleDetails();
}
ngAfterViewChecked() {
this.sortedVehicleDetails = this.vehicleDetails.slice();
}
Seeking solutions for sorting by different properties besides just the name field. How can I enhance the current sorting mechanism?