How can i save pagination, sort, search state of a table in Angular 8? I am using angular2-datatable

1.2k Views Asked by At

I have a table showing a list of items. I clicked on one item in page 3 and navigated to details page of that item. Now after completing task in details page when i navigate back to table page, i want to come in same page 3. current behavior: it navigates to page 1. Reading documentation of Data Tables, I found a property stateSave that saves states. How can i implement it in angular2-datatable? I am using angular2-datatable for displaying items in table.

1

There are 1 best solutions below

5
JsNgian On

There are many ways you can resolve this I think.

  • If you have a state management system you can save the current page in state
  • you can include the page number in router.

I prefer the router way because whenever the URL refreshed or copy paste to another browser it will render the exact page.

const route: Route = [
  {
    path: 'table/:pageNumber',
    component: TableComponent,
  },
  {
    path: 'table/:pageNumber/item',
    component: ItemComponent,
  }
];

use this.router.navigate(['table', 1]); to initially load table

In TableComponent use the below to get the page number on ngOnInit

class TableComponent implements ngOnInit() {
  activePage!: number;

  constructor(private activatedRoute: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.activePage = this.activatedRoute.snapshot.params.pageNumber || 1;
  }
  
  onRowClick() {
   this.router.navigate(['table', this.activePage, 'item'])
  }
}

<table ...
[mfActivePage]="activePage" (mfOnPageChange)="onPageChange($event)>
</table>

This is the whole idea, The router config and routing urls may vary according to you app. Please try this.