I have an Angular 17 application with several sections, and I want to implement smooth scrolling between these sections when the user scrolls the mouse wheel. Specifically, I want the following behavior:
- Each section should scroll into view smoothly when the user scrolls the mouse wheel.
- Scrolling should be disabled while the smooth scroll is happening to avoid interrupting it.
- Each section is an individual component and it has a height of 100vh
Here is my current HTML structure:
<app-menu ></app-menu>
<app-home id="home"></app-home>
<app-about id="about"></app-about>
<app-skills id="skills"></app-skills>
<app-contact id="contact"></app-contact>
How can I achieve this in Angular 17?
What I have tried:
I have implemented the following code in my main component to handle the scrolling logic:
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
sections: string[] = ['home', 'about', 'skills', 'contact'];
currentSectionIndex = 0;
isScrolling = false;
@HostListener('window:wheel', ['$event'])
onScroll(event: WheelEvent) {
if (this.isScrolling) return;
if (event.deltaY > 0) {
this.nextSection();
} else {
this.previousSection();
}
}
nextSection() {
if (this.currentSectionIndex < this.sections.length - 1) {
this.currentSectionIndex++;
this.scrollToSection(this.sections[this.currentSectionIndex]);
}
}
previousSection() {
if (this.currentSectionIndex > 0) {
this.currentSectionIndex--;
this.scrollToSection(this.sections[this.currentSectionIndex]);
}
}
scrollToSection(sectionId: string) {
this.isScrolling = true;
const element = document.getElementById(sectionId);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
setTimeout(() => {
this.isScrolling = false;
}, 1000); // Adjust time to match scroll duration
}
}
}
Thank you for your help!