I need help sorting an Observable Array with Date datatype using the Sort() method in Angular 13. You can find an example at: https://stackblitz.com/edit/ngbootstrap-table-sorting-aabk9h?file=app%2Ftable-sortable.ts
Here is my table-sortable.html:
<ng-container *ngIf="countriesListAll$ | async as countries">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
<th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
<th scope="col" sortable="datewithtime" (sort)="onSort($event)">Dates celebrated</th>
<th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let country of countries">
<th scope="row">{{ country.id }}</th>
<td>
<img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="me-2" style="width: 20px">
{{ country.name }}
</td>
<td>{{ country.area | number }}</td>
<td>{{ country.datewithtime }}</td>
<td>{{ country.population | number }}</td>
</tr>
</tbody>
</table>
</ng-container>
The main difference from the provided example is that I receive the list of countries from the countriesList$ observable.
My table-sortable.ts:
import { Component, Directive, EventEmitter, Input, Output, QueryList, ViewChildren } from '@angular/core';
interface Country {
id: number;
name: string;
flag: string;
area: number;
datewithtime: Date;
population: number;
}
export type SortColumn = keyof Country | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };
const compare = (v1: string | number, v2: string | number) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
// Rest of the code remains unchanged...
@ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;
onSort({column, direction}: SortEvent) {
// resetting other headers
this.headers.forEach(header => {
if (header.sortable !== column) {
header.direction = '';
}
});
// sorting countries
if (direction === '' || column === '') {
this.countriesListAll$= this.countriesListAll$;
} else {
this.countriesListAll$ = this.countriesListAll$.pipe(map(data => data.sort((a, b) => {
const res = compare(a[column], b[column]);
return direction === "asc" ? res : -res;
})));
}
}
}
I am having difficulties sorting the Date field with time included like this format: 21-DEC-2020 14:10:00. How can I properly sort this field?