DEV Community

Anirban Mukherjee
Anirban Mukherjee

Posted on • Updated on • Originally published at

Implement scroll-to-top in Angular

@angular/cli: 12.0.0
Source: GitHub

In this article I would like to talk about an often-used feature on a user-centric application - the scroll-to-top button for allowing a user to quickly scroll to the top of the page, without having to use the mouse. The end result would be something like this:


Let's break up this implementation into 3 steps:

✔️ Set up the scroll-to-top button (with some nice styling).
✔️ Determine when the button should be displayed.
✔️ Scroll to the top of the page on clicking the button.

Set up the scroll-to-top button:

I have used @angular/material for some easy styling. In order to display the button fixed to the bottom-right corner of the page (and some nice hover effects with opacity), I have used the below properties on the :host -


Determine when the button should be displayed:

This is an interesting section. To begin with, we need to set up an Observable on the scroll event of the DOCUMENT. You may directly access the document object, or you may use an InjectionToken<Document>, provided by angular.

This observable starts emitting values as soon as the user starts to scroll up or down. Now we are not really interested in the actual scroll event, but we would like to check something important every time the scroll event is fired - and that is the scroll position. Angular makes this quite simple with the ViewportScroller service from @angular/common package. This service has few useful methods, and I am going to use two of them - getScrollPosition and scrollToPosition.


The getScrollPosition method returns an array of 2 numbers - the X and Y coordinate. I check if the Y coordinate is more than 0 (which means the user has scrolled down) and I enable the scroll-to-top button.

Scroll to the top of the page on clicking the button:

For this last part, I make use of the scrollToPosition method, which again takes in the X and Y coordinates, and I scroll to [0, 0].


Cheers :-)

Discussion (0)