I’m working on an Angular application and I have a function that scrolls smoothly to a specific section on the page. The function works perfectly when I trigger it manually. However, I want the page to automatically scroll to a specific section when the user navigates directly to a URL with a fragment, such as http://localhost:4200/section-2
.
How can I modify my code or implement additional logic to make sure that when the page is loaded with a specific fragment in the URL, it automatically scrolls to that section?
Here’s my current scroll function:
public scrollToSection(sectionId: string): void {
const targetElement = document.getElementById(sectionId);
if (targetElement) {
const navHeight = this.navigationService.getNavHeight();
const yPosition = targetElement.getBoundingClientRect().top + window.scrollY - navHeight;
window.scrollTo({ top: yPosition, behavior: 'smooth' });
}
}