angularhashrouteshashref

How to fix the classic anchor method (id-href) in Angular?


On the homepage component I use scrolling in order to show the different divs of the page. The div looks loke this:

<div id="paragraph1">Paragraph1</div>
<div id="paragraph2">Paragraph2</div>
<div id="paragraph3">Paragraph3</div>

On the same page I have a menu component which links the menu buttons to the corresponding div:

<ul>
   <li><a href="#paragraph1">Paragraph1</a></li>
   <li><a href="#paragraph2">Paragraph2</a></li>
   <li><a href="#paragraph3">Paragraph3</a></li>
</ul>

It seems to work fine: clicking on a menu button leads me to the corresponding div start in the page but it simulaneously throws a console error:

ERROR Error: "Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'paragraph1'

I think it is related to the router.ts config which does not contain the hrefs of the divs:

export const routes: Array<Route> = [
{ path: '/home', component: HomeComponent}];

Any ideas how I can fix the error? Thank you!


Solution

  • Seems like your Angular code is using the HashLocationStrategy, which is interfering with the natural behaviour of the browser to follow the hash segment and move to the appropriate element in the viewport.

    One way is to use the PathLocationStrategy instead. Please see this answer for an example to configure your app this way.