Search code examples
htmlangularroutesanchorhash-location-strategy

Using HTML anchor link fragment in Angular 6


I am working with an Angular 6 project in which I have disabled/removed hash-location-strategy which removes # from URL.

due to this change the link having:

<li routerLinkActive="active">
   <a [routerLink]="['/settings']">Contact Settings</a>
   <ul class="child-link-sub">
      <li>
         <a href="#contactTypes">Contact Types</a>
      </li>
   </ul>
</li>

is no more working it just skips the current components URL and puts #contactTypes after localhost.

I found this github issue which should solve the issue using

<a [routerLink]="['/settings/']" fragment="contactTypes" >Contact Types</a>

which puts #contactTypes at the end of the URL but it doesn't scroll to the top of the browser.

Source: https://github.com/angular/angular/issues/6595


Solution

  • Angular 6.1 comes with an option called anchorScrolling that lives in router module's ExtraOptions. As the anchorScrolling definition says:

    Configures if the router should scroll to the element when the url has a fragment.

    'disabled' -- does nothing (default).

    'enabled' -- scrolls to the element. This option will be the default in the future.

    Anchor scrolling does not happen on 'popstate'. Instead, we restore the position that we stored or scroll to the top.

    You can use it like that:

    const routerOptions: ExtraOptions = {
      useHash: false,
      anchorScrolling: 'enabled',
      // ...any other options you'd like to use
    };
    
    // then just import your RouterModule with these options
    
    RouterModule.forRoot(MY_APP_ROUTES, routerOptions)