Skip to content

Instantly share code, notes, and snippets.

@adrianolsk
Last active July 5, 2024 14:30
Show Gist options
  • Save adrianolsk/9a06ba91cbf8df367634edaa16c9ac5e to your computer and use it in GitHub Desktop.
Save adrianolsk/9a06ba91cbf8df367634edaa16c9ac5e to your computer and use it in GitHub Desktop.
Angular Routing with Hashtag to page anchor
export class PageComponent implements OnInit {
private fragment: string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.fragment.subscribe(fragment => {
if (fragment) {
document.querySelector('#' + fragment).scrollIntoView();
}
});
}
}
<a [routerLink]="['/your-page']" fragment="yourAnchorId">Go to content</a>
...
<div id="yourAnchorId">Content</div>
@BenjaNapo
Copy link

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