angular - Angular 9,滚动恢复/锚滚动不适用于异步数据加载
问题描述
在使用片段通过 routerlink 导航后,我试图滚动到锚点。
** 组件 1 **
<a routerLink="/training/{{ currentTrainingId }}" fragment="{{currentDomainId}}">
这个链接应该把用户带到组件2。我希望通过给元素一个id然后使用片段自动在URL中添加#id来实现锚滚动。
** 组件 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
但是,锚滚动不会发生。我认为这与异步加载数据有关。执行锚点滚动时域尚未加载..
我创建了一个静态 div,然后锚滚动工作。
有谁知道如何处理异步数据和锚滚动?
解决方案
不要依赖自动锚点滚动,而是编写自己的滚动功能。基于@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>
推荐阅读
- r - shinydashboard:为 data.table 中的每个观察结果创建一个超链接,在单击它后进行 API 调用
- django - 如何将现有的 django 数据库用于另一个项目
- nginx - nginx:提供不同反向代理应用程序的静态文件
- sql-server - 如何在 vb.net 睡眠期间在后台运行 .Gif 图像
- php - 根据值跳过导入行
- javascript - 基于for循环添加div类
- php - 测试数据库中是否存在数字,如果存在则创建新的
- powershell - 用于 PowerShell 功能的自定义 -PassThru 开关
- hyperledger-fabric - 以太坊 vs Hyperledger Fabric
- redis - Redis active - 跨数据中心/Kubernetes 集群的主动复制