在Angular 6中使用HTML锚链接#id [英] Using HTML anchor link #id in Angular 6

查看:228
本文介绍了在Angular 6中使用HTML锚链接#id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 6项目,其中我已禁用/删除了从URL中删除#的hash-location-strategy。

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>

不再工作,它只是跳过当前组件URL,并将#contactTypes放在本地主机之后。

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>

这会将#contactTypes放在URL的末尾,但不会滚动到顶部浏览器。

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

来源: https:// github.com/angular/angular/issues/6595

推荐答案

Angular 6.1带有一个名为 anchorScrolling 驻留在路由器模块的 ExtraOptions 。正如 anchorScrolling 定义所述:

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


配置当URL有片段时路由器是否应滚动到该元素。

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

'disabled'-不执行任何操作(默认)。

'disabled' -- does nothing (default).

'已启用'-滚动到元素。

锚定滚动不会在 popstate上发生。相反,我们恢复存储的位置或滚动到顶部。

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

您可以这样使用它:

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)

这篇关于在Angular 6中使用HTML锚链接#id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆