【问题标题】:Navigate to anchor, preserve queryparams and dont reload page导航到锚点,保留查询参数并且不重新加载页面
【发布时间】:2021-01-16 22:18:29
【问题描述】:

我当前的网址是:/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'});

【问题讨论】:

    标签: angular angular11


    【解决方案1】:

    尝试 QueryParamsHandling -merge- angular docu

    【讨论】:

    • 现在锚是正确的,但 url 仍然是错误 404:/home/project%3Fid%3D2?id=3#anchorTest 我也试过 encodeURIComponent(this.router.url) 但同样的问题,为什么网址错误?我想我必须从 this.router.url 中去掉参数?难道没有比手动替换字符更好的解决方案吗?
    • 您似乎在这里将 url 与参数混合...看看您的代码,'%3Fid%3D2' 是 '?id=' 的编码,它不是 url 的一部分
    • this.router.navigate([this.router.url.split('?')[0]], {fragment: anchorName, queryParamsHandling: 'preserve'});我懂了。上面的行有效,但只有一次。如果用户向下滚动然后再次使用锚点,Angular 什么也不做,因为 url 已经相同了。
    【解决方案2】:

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

    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'});
      }
    

    【讨论】:

    • 由于您使用的是 Angular,您可能不想使用 document.getElementById。 Angular 应用程序可能并不总是在浏览器中运行,Angular 它被设计为在多个平台上运行(例如网络工作者/服务器端)。我宁愿使用 elementRef 或 viewChild(我最喜欢的)。
    猜你喜欢
    • 2021-05-24
    • 2020-07-14
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2023-03-22
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多