在使用片段通过路由器链接导航后,我试图滚动到 anchor 。
** 组件 1 **
<a routerLink="/training/{{ currentTrainingId }}" fragment="{{currentDomainId}}">
这个链接应该把用户带到组件 2。我希望通过给元素一个 id 然后在 URL 中使用片段自动添加 #id 来实现 anchor 滚动。
** 组件 2 **
<div *ngIf="all data has been loaded">
....
<domain-overview *ngFor="let domain of domains" [id]="domain.id"></domain-overview>
</div>
生成的 URL 似乎是正确的。
http://localhost:4200/training/28#40
但是, anchor 滚动不会发生。我认为这与异步加载数据有关。执行 anchor 滚动时,域尚未加载。
我创建了一个静态 div,然后 anchor 滚动工作。
有谁知道如何处理异步数据和 anchor 滚动?
解决方案
不要依赖自动 anchor 滚动,而是编写自己的滚动功能。根据@Vinaayakh 他的回答,我得到了以下可行的解决方案。
scroll(id){
const elmnt = document.getElementById(id);
elmnt.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
this.route.fragment.subscribe((fragment: string) => {
this.fragment = fragment;
});
后来,在订阅的完整部分中加载了所有数据后,我调用了滚动函数。
setTimeout(() => {
this.scroll(this.fragment);
}, 250);
最佳答案
尝试添加此功能
scroll(id){
const elmnt = document.getElementById(id);
elmnt.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
并将函数添加到 HTML
<domain-overview *ngFor="let domain of domains" (click)="scroll(id)" [id]="domain.id"></domain-overview>
关于Angular 9,滚动恢复/ anchor 滚动不适用于异步数据加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60562694/