ViewportScroller service in angular

Prateek Singh
1 min readMay 1, 2022

--

In angular ViewportScoller service could be used for adjusting scroll position on the page or disable scroll on the page.

Will be exploring methods provided by this service-

Scroll to an anchor tag (link)

Inject the ViewportScroller service, set id on the anchor tag. method scrollToAnchor accepts anchor tag id. It scroll the page to the anchor.

Scroll to a pixel position on a page (link)

scrollToPosition method could take a two values for x and y position.

using x as 0 and y as 900. This coordinate will make it as a vertical scroll.

Get the current scroll position

The service provides a method to get current scroll position. This found helpful in a case when want to disable scroll when doing modal window or pop over and on dismiss restore the position.

Demo

Browser with console mode on. Logs the scroll position
Demo showing how scroll position works.

First Click

Move the scroll position to bottom of the page using anchor tag position. notice scroll position in console.

Second click

Move to 0,700 position. using position method.

Third Click

It resets the scroll position to top of page.

Thank you for reading.

--

--

Prateek Singh
Prateek Singh

Written by Prateek Singh

I am a full-stack developer. Working on angular, .net, and azure. I like to read about CSS, web design, and authentication.

No responses yet