Angular 2+:如何跳转到主播?

Angular 2+: how to jump to an anchor?

我想使用 angular 路由器 到 jump/scroll 到某个片段(哈希)。 URL 正确生成为 /#section5,但点击时没有任何反应。

经过大量搜索,我发现很多人(e.g.)有同样的问题,有一些解决方法,但没有合适的解决方案。我希望这是一个基本的核心功能。

以下代码不起作用:

<!-- Link --> 
<a routerLink="/" fragment="section5" routerLinkActive="active">Section 5</a>

<!-- Target -->
<div id="section5">Section 5 here</div>

有什么想法吗?

您可以尝试scrollIntoView,在组件的构造函数中添加以下代码

router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    const tree = router.parseUrl(router.url);
    if (tree.fragment) {
      const element = document.querySelector("#" + tree.fragment);
      if (element) { element.scrollIntoView(true); }
    }
  }
});