在 Angular 6 中使用 HTML 锚链接#id

新手上路,请多包涵

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

由于此更改,链接具有:

 <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 之后。

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

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

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

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

原文由 Suresh Karia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 677
2 个回答

Angular 6.1 带有一个名为 anchorScrolling 的选项,它位于路由器模块的 ExtraOptions 中。正如 anchorScrolling 定义 所说:

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

'disabled' -- 什么都不做(默认)。

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

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

你可以这样使用它:

 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)

原文由 Machado 发布,翻译遵循 CC BY-SA 4.0 许可协议

我一直在寻找类似的解决方案并尝试使用 ngx-scroll-to 包,发现它在最新版本的 angular 中不起作用,因此决定研究其他选项并发现我们可以使用 scrollIntoView

HTML代码:

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

代码:

   scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }

原文由 Joel Joseph 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题