'Prevent scroll to top on single router.navigate call in Angular

My Angular 8 app scrolls to top on navigating to new pages. On one specific page I have a sortable table. When navigating to that page it should scroll to top, but when a table header cell is clicked it should update the query params with the sort but not scroll to top.

Is it possible to call router.navigate(...) with the new query param data without triggering a scroll to top, while not disabling scroll to top from the route itself?



Solution 1:[1]

You can configure router module with multiple options. You should be able to preserve scroll with scrollPositionRestoration option.

You can use it like:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'disabled' })

That being said this option will preserve scroll position for all pages.

If you want to achieve this only for a specific page, you have a choice to use navigationExtras in your navigate call and specify current scroll position in state object and upon AfterViewInit handler update scroll position.

Let's say you have a container which contains table, you can use ViewChild decorator to access it in component file.

// declare your container component
@ViewChild("container")
private container: ElementRef;

// after view init updated current scroll position
ngAfterViewInit() {
  const prevScrollPos = this.router.getCurrentNavigation()?.extras?.state?.scrollTop;
  if (prevScrollPos) {
    this.container.nativeElement.scrollTop = prevScrollPos;
  }
}

// specify scroll position on navigation
this.router.navigate(
  ['/login'],
  {
    state: { scrollTop: this.container.nativeElement.scrollTop }
  }
);

Solution 2:[2]

When clicking on anchors, use a @Viewchild in combination with block:'nearest' to prevent the page from jumping to top:

@ViewChild("el") private el: ElementRef;

this.el.nativeElement.scrollIntoView({ behavior: "smooth", block:'nearest' });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kurt Van den Branden