Reputation: 190
How can i disable scrolling to the top when clicking Angular router links? I have three sub routes which i wish navigate between on same parent page and I don't want the app to scroll on top of the page when users click those links. So I want the page to stay in exact same point it was before clicking the link. Is there way to achieve this?
Upvotes: 1
Views: 1901
Reputation: 2680
Add this to the module where you import RoutingModule.forRoot()
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'disabled' })],
This will disable scroll reset for routing in the whole app. If you need more control you can implement a custom logic following a template like this:
class AppModule {
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]);
}
});
}
}
Upvotes: 1