With the Angular component ngx-datatable from Swilane it is possible to use the server-side paging and the server-side sorting.
Both of them are documented, however it is not clear how to combine them and use server side pagination+sorting at the same time.
From the documentation, the pagination automatically calls a callback when the user changes page:
setPage(pageInfo) {
this.page.pageNumber = pageInfo.offset;
this.serverResultsService.getResults(this.page).subscribe(pagedData => {
this.page = pagedData.page;
this.rows = pagedData.data;
});
and the same happens with the sorting:
onSort(event) {
// event was triggered, start sort sequence
console.log('Sort Event', event);
this.loading = true;
// emulate a server request with a timeout
setTimeout(() => {
const rows = [...this.rows];
// this is only for demo purposes, normally
// your server would return the result for
// you and you would just set the rows prop
const sort = event.sorts[0];
rows.sort((a, b) => {
return a[sort.prop].localeCompare(b[sort.prop]) * (sort.dir === 'desc' ? -1 : 1);
});
this.rows = rows;
this.loading = false;
}, 1000);
}
but how to combine them?
I figure out that the best way to handle both server-side pagination AND server-side sorting consist of:
having a
page
object which holds all the pagination and sorting information (like the order column, order direction, page number, page size, ...) which will be bound to the tablehaving a single function
reloadTable()
which calls the API to get the data using the data stored in thepage
object as parameters, automaticaly re-rendering the tablehaving a
pageCallback
which only updates the data contained inpage
relative to the pagination and then callsreloadTable()
having a
sortCallback
which only updates the data contained inpage
relative to the sorting and then callsreloadTable()
example: