【问题标题】:scrollPositionRestoration adding for Angular Child Route为 Angular 子路由添加 scrollPositionRestoration
【发布时间】:2020-08-29 05:49:27
【问题描述】:

在我的 Angular 6 应用程序中,当我向下滚动页面并单击页面底部的链接时,它确实会更改路线并带我进入下一页,但不会滚动到页面顶部。结果,如果第一页(PARENT)很长,而第二页(CHILD)的内容很少,则给人的印象是第二页缺少内容。因为只有当用户滚动到页面顶部时内容才可见。

我尝试为孩子添加“scrollPositionRestoration”,

@NgModule({
  imports: [RouterModule.forChild(routes, {
    scrollPositionRestoration: 'top'
  })],
  exports: [RouterModule]
})

这给了我错误:

(property) scrollPositionRestoration: string
Expected 1 arguments, but got 2.

如何解决这个问题?有什么想法可以滚动 Angular 子组件的页面顶部吗?

【问题讨论】:

标签: angular scroll components parent-child


【解决方案1】:

如果全部失败,则在模板(或父模板)的顶部(或所需滚动到位置)创建一些空的 HTML 元素(例如:div):

<div id="top"></div>

在组件中:

ngAfterViewInit() {
    // Hack: Scrolls to top of Page after page view initialized
    let top = document.getElementById('top');
    if (top !== null) {
      top.scrollIntoView();
      top = null;
    }
  }

【讨论】:

    【解决方案2】:

    我假设您在 AppRoutingModule 中添加了 scrollPositionRestoration 选项,如下所示:

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

    如果您的样式表中有以下代码:

    html,
    body {
      height: 100%;
    }
    

    您的滚动到顶部会中断! ¡#$%&*+@#!

    您可以删除此属性,或者将您的代码更改为:

    html {
      min-height: 100%;
      display: flex;
    }
    body {
      min-height: 100%;
      flex: 1;
    }
    

    注意!请小心更改样式表,因为它可能会破坏其他内容...

    【讨论】:

      【解决方案3】:

      使用 ViewportScroller

      ts:

      import { ViewportScroller } from '@angular/common';
      
      constructor(private viewportScroller: ViewportScroller){
      }
      
      public scrollTo(anchor: string): void { // for calling to anchors
          this.viewportScroller.scrollToAnchor(anchor);
      }
      
      ngOnInit(){
          this.viewportScroller.scrollToPosition([0, 0]);
      }
      

      html:

      <div id="srollingEl"></div>
      <button (click)="scrollTo('srollingEl')"></button>
      

      【讨论】:

        猜你喜欢
        • 2018-08-30
        • 2022-09-28
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        • 2017-01-07
        • 2018-11-17
        相关资源
        最近更新 更多