首页 > 解决方案 > 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);

标签: angularasynchronousanchor

解决方案


尝试添加此功能

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>

推荐阅读