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>
@glatrofa
Copy link

glatrofa commented Jul 2, 2020

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.

@ayoubkhan558-zz
Copy link

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 👍

@Brosinski
Copy link

None of these solutions work...

@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