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' });
}
}
2
Answers
Note: People may be more helpful if you write your questions more clearly.
I’m not sure if I understood it correctly, but you can use these methods; I haven’t tested the codes but it should work.
Angular;
If you defined the "section-2" part as a parameter as ":elementid" when defining routes;
Option 1: (Is static value. When it changes, it can be difficult to keep track.)
Option 2: (It can be tracked.)
Pure JS in Angular;
(There are other methods, too.)
(It is generally recommended to use the angular method instead of js in Angular.)
HomeComponent
.routes
in theprovideRouter
function.<router-outlet>
in the template in the main.ts. Remove the imports of the section components from theApp
.Demo @ StackBlitz