Handling scrolling on Angular router transitions

Sébastien Dubois
Frontend Weekly
Published in
7 min readMay 12, 2020

--

By default, when a new route is activated, Angular’s router doesn’t touch the scroll position. At least this is still true of Angular 9, even if it’ll probably change in the future.

This is problematic in some cases. For instance, if you are on a page that ends up being longer that the viewport, scroll down and navigate to a new route (e.g., using a routerLink), then if the new page is also longer than the viewport, the scrollbar will not be at the top. Not that great since you won’t see the top of the page.

Also, if you navigate back/forward using the browser’s buttons, the scroll position will not be restored either. A sad situation indeed…

Fortunately, there are different solutions to fix that. Let’s see how.

Bazooka approach

When a new route is activated, an “activated” event is emitted, which you can react to. So you could do something like this:

--

--