I have a bootstrap HTML table (operated by ng-bootstrap for Angular and utilized NgbdSortableHeader to arrange table columns by clicking on the column). When I click on an element, it sorts the column in ascending, descending, or ''(none) order.
HTML TABLE HEADERS
<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="population" (sort)="onSort($event)">Population</th>
</tr>
SORTING METHOD
@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 === "") {
this.countries = COUNTRIES;
} else {
this.countries = [...COUNTRIES].sort((a, b) => {
const res = compare(a[column], b[column]);
return direction === "asc" ? res : -res;
});
}
}
Whenever onSort is triggered via clicking on a column header, it arranges the countries array and updates the table accordingly.
ngOnInit() {
this.onSort({ column: "population", direction: "asc" });
}
However, when calling the onSort method in onInit(), it doesn't work. How can I make this function work programmatically by calling the onSort function?
Link to functional StackBlitz example: https://stackblitz.com/edit/ngbootstrap-table-sorting-vfwu4m?file=app/table-sortable.ts