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

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

问题描述

我正在处理一个 Angular 6 项目,在该项目中我已禁用/删除了从 URL 中删除 # 的 hash-location-strategy.

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>

不再起作用,它只是跳过当前组件 URL 并将 #contactTypes 放在 localhost 之后.

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

我发现这个 github 问题应该使用

<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).

'enabled' -- 滚动到元素.此选项将成为未来的默认选项.

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

锚滚动不会发生在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天全站免登陆