0

我当前的网址是:/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]], {fragment: anchorName, queryParamsHandling: 'preserve'});
4

2 回答 2

0

尝试 QueryParamsHandling -merge- 角度文档

于 2021-01-07T14:04:50.600 回答
0

我们找到了另一种方法来让它工作而无需重新加载或弄乱参数。

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'});
  }
于 2021-01-16T14:18:29.007 回答