Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep scroll position when you return back and change routes angular 5

I load some results of employees and I am using pagination 20 results per page. When I scroll on the last one of the first page I click on this and the user is redirected to another page, when the user clicks the back button they return back to search results but the scroll position has been lost. Any recommendations of how can I maintain it?

like image 678
BillUser88 Avatar asked Sep 02 '25 15:09

BillUser88


2 Answers

Angular has some extra options you can apply when importing your Router Module, which may suit your requirements.

https://angular.io/api/router/ExtraOptions#scrollPositionRestoration

They have an example for component specific scrolling. I have never tried it myself, but it seems to match what you're trying to achieve.

like image 167
Wingnod Avatar answered Sep 05 '25 05:09

Wingnod


Adding this into you're app.component.ts file do the trick, as said by wingnod.

export class AppComponent {
  constructor(router: Router, viewportScroller: ViewportScroller) {
    router.events.pipe(
      filter((e: Event): e is Scroll => e instanceof Scroll)
    ).subscribe(e => {
      if (e.position) {
        // backward navigation
        viewportScroller.scrollToPosition(e.position);
      } else if (e.anchor) {
        // anchor navigation
        viewportScroller.scrollToAnchor(e.anchor);
      } else {
        // forward navigation
        viewportScroller.scrollToPosition([0, 0]);
      }
    });
  }
}

The reason of this behavior is that page didn't already render and scrollToPosition no have effect. There are not a good hack with timeout but it works. DrDager

Note

Angular have actually an open issue regarding this problem

like image 31
Raphaël Balet Avatar answered Sep 05 '25 06:09

Raphaël Balet