0
votes

I am using angular material to display data in table with pagination, when the user clicks on a row, I redirect him to another page, and if he wants to go back to table page, he clicks on a button.

My problem is the user needs to go back to table page and to scroll to the specific row, I do it like this

document.getElementById(elementId).scrollIntoView()

but if the row clicked is not in the first page, the element is not found, how can I paginate to the page where the row exists ?

And the second problem is user can filter table then select a specific row, if I save the page number, when he will go back to table page, the data will be rendered without filter and the page number will not be correct

2

2 Answers

2
votes

you have to save the information about pageIndex when you go to another page, because when you come back your data table you have to give this index number to [pageIndex]. Ex:

<mat-paginator [length]="length"
          [pageSize]="pageSize"
          [pageSizeOptions]="pageSizeOptions"
          (page)="pageEvent = $event"
          [pageIndex]="pIndex">
</mat-paginator>

here pIndex is a variable that I define in my Component. if your pageSize is 10 and pageIndex is 0 then it show 1 to 10 row...

For more info: https://stackblitz.com/angular/ngdejmepgbr?file=app%2Fpaginator-configurable-example.html

2
votes

You need to connect the paginator with Angular's router.

For example, let's say you structured your route path as follows:

http://my/url/to/table/component?page=2

In this case you can get the page index 2 from the url to the table as follow:

Component Class:

class MyComponent {

  pageIndex = this.activatedRoute.queryParams.pipe(
    map(params => params['page'])
  );

  constructor(activatedRoute: ActivatedRoute) {}
}

Template:

<mat-paginator [pageIndex]="pageIndex | async"></mat-paginator>

So far the URL will drive the table. Now you also need to update the URL when the user navigates the table using the paginator:

Template:

<mat-paginator [pageIndex]="pageIndex | async" (page)="pageChange($event)"></mat-paginator>

Component Class:

class MyComponent {

  pageIndex = this.activatedRoute.queryParams.pipe(
    map(params => params['page'])
  )

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

  pageChange(e: PageEvent): void {
    this.router.navigate( /* ... */ );
  }
}

Now that the URL is being updated as the user navigates around the table, that allows the router to then drive the table when the user returns to a previously visited URL.