【问题标题】:Angular 10 Scroll location on back buttonAngular 10后退按钮上的滚动位置
【发布时间】:2020-10-21 13:58:20
【问题描述】:

当用户按下浏览器后退按钮时,我在获取正确的滚动位置时遇到了一些问题。 目前需要加载的异步数据需要很长时间,因此在数据完成之前滚动只是部分。

如果我为容器 div 使用固定高度,则滚动恢复按预期工作。

关于如何解决此问题的任何想法?

以下是我的滚动恢复失败的路线的相关部分。 processProdTypQuery 方法检查路由器参数,如果需要,只向articleOutput$ 发送新数据。 articlesView 用作模板中哑组件的输入。

articles-route.component.ts

export class ArticlesRouteComponent implements OnInit {

  articlesView: Article[];

  constructor(
    private route: ActivatedRoute,

    // Service that collects article data from API
    private article: articleService,

    // Service that takes an article list as input, filters it and outputs a new list
    private articleFilter: ArticleFilterService) {

    this.articleFilter.articleOutput$.subscribe(output => {
      this.articlesView = output;
    });
  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.articleFilter.processProdTypQuery(params);
      this.article.processProdTypQuery(params);
    });
  }
}

在路由器模块中启用滚动恢复如下,

@NgModule({
  imports: [ RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled'
    })
  ],
  exports: [ RouterModule ]
})

【问题讨论】:

  • 你试过在选项中使用 scrollOffset: [0, 0] 吗?
  • 你的意思是我应该保存偏移量并在加载异步数据时恢复它?

标签: angular


【解决方案1】:

我会添加我自己的解决方案,尽管它可能不是最佳答案。希望它仍然可以帮助其他人。

我没有试图弄清楚滚动恢复的角度处理,而是将 Y 滚动位置保存在 ngOnDestroy 上的文章列表服务中

export class ArticlesRouteComponent implements OnInit, OnDestroy {

  articlesView: Article[];

  constructor(
    private route: ActivatedRoute,

    // Service that collects article data from API
    private article: articleService,

    // Service that takes an article list as input, filters it and outputs a new list
    private articleFilter: ArticleFilterService) {

    this.articleFilter.articleOutput$.subscribe(output => {
      this.articlesView = output;

      this.articleFilter.restoreScrollPosition();
    });
  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.articleFilter.processProdTypQuery(params);
      this.article.processProdTypQuery(params);
    });
  }
  
  ngOnDestroy() {
    this.articleFilter.scrollPosition = window.scrollY;
  }
}

this.articleFilter.restoreScrollPosition() 滚动恢复方法可能应该在其他地方运行,因为它需要超时才能正常工作。

restoreScrollPosition() {
    window.setTimeout(() => {
      window.scrollTo({behavior: 'smooth',top:this.scrollPosition, left:0});
    }, 200);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 2019-04-13
    • 2015-05-26
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多