Angular 9 没有导航到锚点

Angular 9 Doesn't Navigate to Anchor

我有一个 angular 应用程序,我正在尝试 link 通过锚点和代码导航到页面上的特定位置。我已经使用以下 ExtraOptions:

设置了路由器
const routerOptions: ExtraOptions = {
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled'
};

我正在使用以下代码进行导航:

this.router.navigate(['/home'], {fragment: 'tasks'}).then(success => {
  if (!success) {
    console.log('Error navigating to home');
  }
});

这确实将锚点放在 url 的末尾,所以它变成了 http.../home#tasks,这看起来是正确的。但是,不是滚动到靠近顶部的 'tasks' 锚点,而是一直滚动到页面底部。我还尝试将 scrollPositionRestoration 属性 设置为 topdisabled,但似乎都没有任何改变。

我在主页上确实有内部 links 可以滚动到有问题的锚点,它们按预期工作,所以我知道锚点在正确的位置和所有内容。

我错过了什么?如何让它正确滚动到锚点?我也做了 Google 这个并发现了几件事让我找到了上面的代码但是我还没有找到任何其他东西所以据我所知这应该有效。

我还没有使用过这个功能,但是看到了这个sample
而且我没有看到你的代码,很难说出哪里出了问题。也许你有另一个带有任务 ID 或...的项目?
但也试试这个我希望它能帮助你:

  constructor(private loc: Location, private router: Router, private viewportScroller: ViewportScroller) {
this.router.events.pipe(filter(e => e instanceof Scroll)).subscribe((e: any) => {
  console.log(e);

  // this is fix for dynamic generated(loaded..?) content
  setTimeout(() => {
    if (e.position) {
      this.viewportScroller.scrollToPosition(e.position);
    } else if (e.anchor) {
      this.viewportScroller.scrollToAnchor(e.anchor);
    } else {
      this.viewportScroller.scrollToPosition([0, 0]);
    }
  });
});
}