Search code examples
angularroutesfragmentmarkdownhistory

angular history route and fragment


my angular app use the history route path

localhost/blog/article/:id

when this route on open localhost/blog/article/123456, httpclient get some markdown content data and render

the markdown content

- [one](#one)
- [two](#two)

# one
some thing

# two
some thing

render html

<a herf="#one">one</a>
<a herf="#two">two</a>
<h1 id="one">one</h1>
<p>some thing</p>
<h1 id="two">one</h1>
<p>some thing</p>

but click the a tag redirect to root path

how to scroll to the fragment when clicking on a tag

---------UPDATE---------

The problem has been solved

refer to here


Solution

  • You need to enable anchorScrolling in RouterModule.forRoot() like below :-

    RouterModule.forRoot({anchorScrolling: true})
    

    And use fragment attribute to assign the fragment like above instead of href.

    <a [routerLink]='"."' [fragment]="one">Dashboard</a>
    

    You can read about it here :-

    https://medium.com/dev-genius/advanced-router-configuration-in-angular-d22c6dc420be

    Or :-

    https://angular.io/api/router/ExtraOptions