ViewportScroller in Angular as Programmatic Scrolling

Posted on 2025-05-23 by Burak Hamdi TUFAN
Web
ViewportScroller in Angular as Programmatic Scrolling
Hello everyone, in this article we are going to talk about the ViewportScroller service within Angular which is an integral part of any modern web applications.

Lets get started.

What ViewportScroller service does?

In Angular framework, ViewportScroller service provides provides a built-in solution to handle the scrolling the programmatically. With ViewportScroller service developers can scroll to specific elements, restore the previous position of the page, even change the scrolling coordinates of the page directly.

What is ViewportScroller service?

ViewportScroller is an Angular built-in service which is inside the @angular/common package which enable us to scroll to target position on the page. It also works well with angular router and we can handle the scrolling after even route changed to saved last position easily.

What ViewportScroller service used for basically:

  • Scrolling to a specific element or position
  • Saving and restoring scroll position
  • Implementing smooth scrolling behavior
  • Managing anchor scrolling to the target section on route changes (with #section1)

Let's make some examples about ViewportScroller service now.

Firstly we need to import the service from @angular/common and inject in in the required component that we want to use in. And we can create our required methods to handle the operrations like below.

import { ViewportScroller } from '@angular/common';

@Component({
  selector: 'app-scroll-demo',
  templateUrl: './scroll-demo.component.html',
})
export class ScrollDemoComponent {
  constructor(private viewportScroller: ViewportScroller) {}

  scrollToTop(): void {
    this.viewportScroller.scrollToPosition([0, 0]);
  }

  scrollToAnchor(anchorId: string): void {
    this.viewportScroller.scrollToAnchor(anchorId);
  }

  getCurrentScrollPosition(): [number, number] {
    return this.viewportScroller.getScrollPosition();
  }
}

As you can see above we have used some methods above.

scrollToPosition(position: [number, number]):
Handles the scrolling to a specific (x, y) position in the page. We can call the method like below and it will scroll down with 200px and 50px to the right

this.viewportScroller.scrollToPosition([50, 200]);
scrollToAnchor(anchor: string)
Scrolls to a specified DOM element with a matching id. Works similar to anchor links (#my-section). We can call the method like below and it will scroll to specified section automatically. For sure, We need to specify this id in the template side to be found.

Component .ts file


this.viewportScroller.scrollToAnchor('my-blog-section');

Component .html file


<section id="my-blog-section">Target Section</section>
getScrollPosition(): [number, number]
It returns the current scroll position as [x, y] coordinates. Whenever we get the coordinates we can keep it in the memory and use it again with the scrollToPosition method.

const [x, y] = this.viewportScroller.getScrollPosition();
console.log(`Current position: x=${x}, y=${y}`);

setOffset(offset: () => [number, number])
This method sets an offset for anchor scrolling. This method is useful if you have a fixed header in the page. Below code block will set an offset for scrolling as 60px.

ngOnInit(): void {
  this.viewportScroller.setOffset(() => [0, 60]); 
}

Enabling scroll restoration after navigation
Angular also allows the scroll position restoration when navigating happens. We can configure this in the RouterModule:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled', // or 'top'
      anchorScrolling: 'enabled',
    }),
  ],
})
export class AppRoutingModule {
...
}

Here anchorScrolling: 'enabled' allows automatic anchor scrolling.

Here we also have two options for scrollPositionRestoration

  • enabled: restores the previous scroll position on navigation.
  • top: scrolls to top on every navigation.
Smooth Scrolling
ViewportScroller does not natively support smooth scrolling. But, we can achieve it using native DOM methods or libraries like scroll-behavior. Here is an example for it:

scrollToElementSmooth(id: string): void {
  const el = document.getElementById(id);
  if (el) {
    el.scrollIntoView({ behavior: 'smooth' });
  }
}

Conclusion

ViewportScroller service in Angular is effective utility to manage the scrolling. It is also integrated with Angular Native router and this makes it working easily with Angular Router and DOM elements. In Angular whenever you need a proper solution for scroll behaviour, ViewportScroller offers a robust, Angular-native solution for you.

That is all.

Happy scrolling.

Burak Hamdi TUFAN


Tags
Share this Post
Send with Whatsapp