- It is recommended to create a wrapping component for all sections. Within this component, extract the initial route path and navigate to the corresponding section.
home.component.ts
import { Component } from '@angular/core';
import { Section1Component } from '../section1/section1.component';
import { Section2Component } from '../section2/section2.component';
import { Section3Component } from '../section3/section3.component';
import { Section4Component } from '../section4/section4.component';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { NavigationService } from '../navigation.service';
@Component({
selector: 'app-home',
standalone: true,
imports: [
Section1Component,
Section2Component,
Section3Component,
Section4Component,
CommonModule,
],
template: `
<app-section1></app-section1>
<app-section2></app-section2>
<app-section3></app-section3>
<app-section4></app-section4>
`,
})
export class HomeComponent {
name = 'Angular';
constructor(
private activatedRoute: ActivatedRoute,
private navigationService: NavigationService
) {}
ngOnInit(): void {
this.activatedRoute.pathFromRoot &&
this.activatedRoute.pathFromRoot.length > 0 &&
this.activatedRoute.pathFromRoot[1].url.subscribe((url) => {
let elementId = url[0].path;
this.scrollToSection(elementId);
});
}
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' });
}
}
}
- In your routing configuration, ensure that all section URLs are directed to the
HomeComponent
.
app.route.ts
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: 'section-1', component: HomeComponent },
{ path: 'section-2', component: HomeComponent },
{ path: 'section-3', component: HomeComponent },
{ path: 'section-4', component: HomeComponent },
{ path: '**', redirectTo: '' },
];
- Include the
routes
in the provideRouter
function.
main.ts
import { routes } from './app/app.routes';
bootstrapApplication(App, {
providers: [provideAnimations(), provideRouter(routes)],
}).catch((err) => console.error(err));
- Make sure to use the routes and render the appropriate component. Add the
<router-outlet>
in the template within main.ts. Remove the imports of the section components from the App
.
main.ts
@Component({
selector: 'app-root',
standalone: true,
imports: [
NavComponent,
CommonModule,
RouterModule,
],
template: `
<div class="container">
<app-nav></app-nav>
<router-outlet></router-outlet>
</div>
`,
})
View Demo on StackBlitz