Using anchor link #id in Angular 6

2019-01-23 20:14发布

I am working with 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 current components URL and puts #contactTypes after localhost.

I found this link 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

4条回答
手持菜刀,她持情操
2楼-- · 2019-01-23 20:19

You need to use hash routing strategy to enable the hash scrolling.

you need to give second argument as an object like RouterModule.forRoot([],{useHash:true}}. It will work.

查看更多
女痞
3楼-- · 2019-01-23 20:26

use ngx page scroll

 <a pageScroll href="#awesomePart">Take me to the awesomeness</a>
 <h2 id="awesomePart">This is where the awesome happens</h2>
查看更多
仙女界的扛把子
4楼-- · 2019-01-23 20:39

I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular so decided to look into other option and found that we can use scrollIntoView

HTML code :

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

Ts code :

  scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
查看更多
再贱就再见
5楼-- · 2019-01-23 20:44

Angular 6.1 comes with an option called achorScrolling 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)
查看更多
登录 后发表回答