What is scrollTop?

As per MDN docs The Element.scrollTop property gets or sets the number of pixels by which an element’s content is scrolled from its top edge. This value is subpixel precise in modern browsers, meaning it isn’t necessarily a whole number.

How can we get or set the scrollTop position for the document in Angular?

In AngularJS (Angular v1) –
We have to use vanilla JS code something like below-

window.scrollY
 	or
window.pageYOffset

Both outputs the same.

Note – the below example uses AngularJS (version 1) and explains the step-by-step implementation of scroll-to-top functionality using a directive.

1. Create the scroll directive


2. Add styling for the button


3. Use the directive in HTML

 

Below you can find the whole code for AngularJS(version 1).

 


    
    
    Angular Version 1
    
    


    

In Angular 2 +, we can use the @HostListener directive which will handle the scroll events for us.

What is the @HostListener directive in Angular?

HostListener is a decorator in Angular that allows us to listen for events on the host element of a component or directive. It enables us to add an event handler to a DOM element and respond to events such as clicks, key changes, scrolls, and more. By binding a component method to a specific event, we can execute that method when the event is triggered.

Note – The below example uses Angular 18, the code would be similar to the previous version we just need to register the custom directive under a module.

Below is an example of handling a scroll event for the above-mentioned link issue-

1. Create a directive named ScrollDirective.

import { Directive, EventEmitter, HostListener, Output } from '@angular/core';
@Directive({
  selector: '[scroll]',
  standalone: true
})
export class ScrollDirective {
  @Output() scrollPosition: EventEmitter = new EventEmitter
    ();
  @HostListener('window:scroll', ['$event'])
  updateScrollPosition(e: any) {
    this.scrollPosition.emit(e.target.scrollingElement.scrollTop);
  }
}

2. Use the ScrollDirective to a module.

import { Component } from '@angular/core';
import { ScrollDirective } from '../directives/scroll.directive';
@Component({
  selector: 'app-mock-data',
  standalone: true,
  imports: [ScrollDirective],
  templateUrl: './mock-data.component.html',
  styleUrl: './mock-data.component.css'
})
export class MockDataComponent {
  currentScrollPosition = 0;
  topPosToStartShowing = 100;
  isShow = false;

}

3. Use the directive on the HTML component after registering and listen for changes in the scroll position.

Current Scroll Postion: {{currentScrollPosition}}

Lorem ipsum odor amet, consectetuer adipiscing elit. Erat efficitur euismod cras magnis suscipit placerat. Accumsan magna ut netus ad maximus turpis? Class justo leo pretium metus torquent quam arcu ante donec. Vivamus erat rhoncus tellus scelerisque eu commodo. Viverra tincidunt sociosqu platea vel netus interdum. Nulla venenatis inceptos; odio ante ullamcorper habitasse maximus sem. Rutrum praesent facilisi ullamcorper sed est neque auctor curae. Nam nibh aliquet est natoque molestie ultrices cras aliquet. Amet rutrum consequat rutrum, netus. Scelerisque porta torquent, tortor vestibulum odio scelerisque hac! Gravida nisi varius class nec finibus. Parturient ex leo urna quisque sociosqu sodales, nisi nibh eros.

@if (isShow) { }

4. Change the scroll position in a new method named scrollChanged to handle the condition for the Goto Top button.

scrollChanged(scrollPosition: number) {
    this.currentScrollPosition = scrollPosition;
    if (scrollPosition >= this.topPosToStartShowing) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  }

5. Register the gotoTop method in the TS file to scroll the page to the top with smooth behaviour.

gotoTop() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }

The final TS code would be like the below-

import { Component } from '@angular/core';
import { ScrollDirective } from '../directives/scroll.directive';


@Component({
  selector: 'app-mock-data',
  standalone: true,
  imports: [ScrollDirective],
  templateUrl: './mock-data.component.html',
  styleUrl: './mock-data.component.css'
})
export class MockDataComponent {
  currentScrollPosition = 0;
  topPosToStartShowing = 100;
  isShow = false;
  scrollChanged(scrollPosition: number) {
    this.currentScrollPosition = scrollPosition;
    if (scrollPosition >= this.topPosToStartShowing) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  }
  gotoTop() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }
}

Support On Demand!

Angular