I have a web app in angular 16 with home page with menu and several components inside which contain an id as anchor. What I want is to reach one component in the home page by clicking on a menu item.
Here are my files look like :
my app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CUSTOM_ELEMENTS_SCHEMA, } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import HomeModule from './components/home/home.module';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HomeModule
],
providers: [],
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {
}
My app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
initialNavigation: 'enabledBlocking',
onSameUrlNavigation: 'reload',
scrollPositionRestoration: 'enabled'
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
My HomeComponent.html
<nav>
<div class="item-menu-wrapper">
<a [routerLink]="'/'" fragment="section1" class="item-menu">section1</a>
<a [routerLink]="'/'" fragment="section2" class="item-menu">section2</a>
<a [routerLink]="'/'" fragment="section3" class="item-menu">section3</a>
<a [routerLink]="'/'" fragment="section4" class="item-menu">section4</a>
</div>
</nav>
<div>
<app-landing-page></app-landing-page>
<app-section1></app-section1>
<app-section2></app-section2>
<app-section3></app-section3>
<app-section4></app-section4>
</div>
One of my section component
<div>
<h1 id="section1">This is my section</h1>
<p>lorem ipsum....</p>
</div>
Each section is a standalone component with his own module which is imported in the home.module.ts.
What I tried to do but doesn't work :
- use 'href= "#section1"'
- use ngx-page-scroll package like here but seems last angular 16 update is not supported
My last solution is what you can see above by using fragments. I follow many threads like here or here
Have I missed something ? Why anything works ?
Thanks in advance for your help