Angular: error on anchor scrolling with fragments

Viewed 173

So, I have this header.component.ts on my project, with links to all sections of the home page.

        <nav class="nav-menu d-none d-lg-block">
        <ul>
            <li class="active"><a [routerLink]="['/']" [routerLinkActive]="'active'">Home</a></li>
            <li><a [routerLink]="['/']" fragment="portfolio" [routerLinkActive]="'active'">Portfólio</a></li>
            <li><a [routerLink]="['/']" fragment="services" [routerLinkActive]="'active'">Serviços</a></li>
            <li><a [routerLink]="['/']" fragment="contact" [routerLinkActive]="'active'">Contato</a></li>
        </ul>
    </nav>

I've changed my app.routing.module so anchor scrolling is enabled:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      anchorScrolling: 'enabled'
    })
  ],
  exports: [RouterModule]
})

Problem is: everytime I click on a link, instead of scrolling to the section with the related id, my page goes back to the top. Is there anything that I am doing wrong?


Edit: I've created a stackblitz here, however its getting a compiler error

2 Answers

You have to add ids to your responsive sections since Angular will automatically scroll to the element with the id of the given fragment.

Got to the answer. It turned out to be a problem on a script on the template I was using. Once I removed the script (which was made to provide smooth the scrolling), my problem was solved. Thank you @divin-irakiza and @chellappan-வ for the help!

Related