Last active
July 5, 2024 14:30
-
-
Save adrianolsk/9a06ba91cbf8df367634edaa16c9ac5e to your computer and use it in GitHub Desktop.
Angular Routing with Hashtag to page anchor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class PageComponent implements OnInit { | |
private fragment: string; | |
constructor(private route: ActivatedRoute) { | |
} | |
ngOnInit() { | |
this.route.fragment.subscribe(fragment => { | |
if (fragment) { | |
document.querySelector('#' + fragment).scrollIntoView(); | |
} | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a [routerLink]="['/your-page']" fragment="yourAnchorId">Go to content</a> | |
... | |
<div id="yourAnchorId">Content</div> |
Hi, your code works well but the second time the link is clicked the page scroll not works. I solved not using your page.component.ts code and declaring the routes in app.module.ts as a constant:
import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'yourPath', component: YourComponent}, // other paths ];and then I add some options to the forRoot method of RouterModule:
RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload', anchorScrolling: 'enabled', enableTracing: false }),Now the page scroll works even if the scroll link is clicked many times.
Works fine : Thanks 👍
None of these solutions work...
In my case I had to add "anchorScrolling" in the file app.config.ts:
export const appConfig: ApplicationConfig = {
providers: [provideRouter(
routes,
withComponentInputBinding(),
withInMemoryScrolling({scrollPositionRestoration: "top", anchorScrolling: "enabled"})),
provideClientHydration()
]
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, your code works well but the second time the link is clicked the page scroll not works. I solved not using your page.component.ts code and declaring the routes in app.module.ts as a constant:
and then I add some options to the forRoot method of RouterModule:
Now the page scroll works even if the scroll link is clicked many times.