Tracking scroll position in Angular

Suyog Ghinmine
2 min readOct 15, 2020

By the end of this tutorial you’ll have a nifty little project, where you can keep track of what section of your webpage the user is on.

You could further extend or include this in your existing project.

To get started, create a new Angular project. Use the below html template in app.component.html :

Add the following styling in your app.component.scss:

Now you have four sections of different colours, 100% width and height of 100 vh (view port height). Something like this:

Now that you are all set up, let’s move to the actual problem.

Create a service, scroll.service.ts

Create a BehaviourSubject, it is going to keep emitting the name of the current section. Initially, the user is going to be on the home section, so:

currentSection: BehaviorSubject<String> = new BehaviorSubject('home');

The array sections is an array of string, containing the names of all the existing section on our page.

sections: string[] = ['home','about','features','contact']

Now go ahead and create a function called keepTrack().

keepTrack() {
const viewHeight = window.innerHeight;
for (var section of this.sections) {
const element = document.getElementById(section);
if (element != null) {
const rect = element.getBoundingClientRect();
if (rect.top >= 0 && rect.top < viewHeight / 2)
{this.currentSection.next(section);}
}
}
}

The variable viewHeight holds the value of the inner height of the window.

You loop through all your sections to check which one is in view.

The condition I implemented is that if the top of the section is greater than 0 and if it is less than half of the inner height of the window (basically, the top of the section falls in the first half of the screen), the section is in view.

Now we need to make sure that this function is called every time the screen is scrolled. For that, use document.addEventListener on the scroll event.

document.addEventListener('scroll', () => {
this.keepTrack();
})

That’s it, you are done!

Now to check if this works, in the constructor of your app.component.ts, subscribe to the BehaviourSubject and that’s that.

constructor(
private scrollService: ScrollService
)
{
scrollService.currentSection.subscribe(
(res) => {
console.log("current section: ", res)
}
)
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Suyog Ghinmine
Suyog Ghinmine

No responses yet

Write a response