Search code examples
angulartypescriptangular-router

Angular 8 scroll to a fragment, doesn't bring the fragment to the top of the page


I have a link, by clicking on the link, I want to scroll to a fragment which is at the bottom of the page. When I click on the link, the fragment is working, but it doesn't bring it to the top of the page.

I tried having the using div and section with an id to create the fragment. But, it doesn't bring the div or section to the top of the page.

The code in my app routing module is:

 imports: [
    RouterModule.forRoot(routes, {
    //useHash: true,
    scrollPositionRestoration: 'enabled',
    onSameUrlNavigation: 'reload',
    anchorScrolling: 'enabled'
  })]

My component code for link and fragment:

<a [routerLink]="['/proposal']" fragment="dcn">{{ dcn }}</a>

<section id="dcn">
Some other html here
</section>

Note, I have tried using useHash:true, but it doesn't seem to work. I would prefer a solution without useHash to be true.


Solution

  • I use code like this to scroll to element:

    HTML:

    <button (click)="scroll(target)"></button>
    <div #target>Your target</div>
    

    TS:

    scroll(el: HTMLElement) {
        el.scrollIntoView();
    }
    

    Maybe this helps you.

    Remember: to page scroll to element, page must have sufficient contents do generate a scroll/scrollbar, otherwise does not have content to scroll.