导航到锚点,保留查询参数并且不重新加载页面
Navigate to anchor, preserve queryparams and dont reload page
我目前的url是:/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>
此外,当我再次点击它时,我不想要这个 url,当然只是一个锚点:/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'});
试试 QueryParamsHandling -merge-
angular docu
我们找到了另一种使其工作的方法w/o重新加载或乱用参数。
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'});
}
我目前的url是:/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>
此外,当我再次点击它时,我不想要这个 url,当然只是一个锚点:/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'});
试试 QueryParamsHandling -merge- angular docu
我们找到了另一种使其工作的方法w/o重新加载或乱用参数。
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'});
}