导航到锚点,保留查询参数并且不要重新加载页面

问题描述

我当前的网址是:/home/project?id=3,我想在不重新加载页面的情况下转到 /home/project?id=3#anchorTest .所以基本上我想向下滚动到锚点。如何最好地做到这一点?

  public gotoAnchor(anchorName: string): void {
    this.router.navigate([this.router.url],{fragment: anchorName}); // Goes all wrong regarding the queryparams
  }

也失败了:

<a [routerLink]="<What to use here to preserve the queryparams?>" fragment="anchorTest">Goto test</a>

另外,当我再次点击它时,我不想要这个网址,当然只是一个锚点:/home/project?id=3#anchorTest#anchorTest

这给出了一个 404:

  public gotoAnchor(anchorName: string): void {
    this.router.navigate([this.router.url],{fragment: anchorName,queryParamsHandling: 'preserve'}); // Error 404: /home/project%3Fid%3D2?id=3#anchorTest
  }

这只能执行一次(因为第二次调用时url是相同的)

this.router.navigate([this.router.url.split('?')[0]],queryParamsHandling: 'preserve'});

解决方法

试试 QueryParamsHandling -merge- angular docu

,

我们找到了另一种无需重新加载或修改参数即可使其工作的方法。

HTML:

<h1 id="top">Title - Foo</h1> <!-- Scroll to this element -->
<!-- Other code here -->
<li><a role="button" (click)="navClick('top')">Top</a></li>

打字稿:

  public navClick(elementId: string): void {
    document.getElementById(elementId)?.scrollIntoView({behavior: 'smooth'});
  }