在处理静态标题和内容容器溢出时,如何在加载不同组件后重置滚动位置?

问题描述 投票:0回答:2

正在寻找滚动问题的良好解决方案:)

初始设置

我的一般应用程序结构如下所示:

  • 主容器(应用程序组件 -> 固定 100vh 大小的 div):
    • 标题(带有应用程序标题和固定大小的div)
    • 内容(带有路由器出口和溢出的div:自动)-固定大小100vh-标题高度
<div>
  <div class="app-header">
    <app-header></app-header>
  </div>

  <div class="app-content">
    <router-outlet></router-outlet>
    <div class="app-footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

在内容容器中,我加载工具组件,其中加载不同的其他小步骤组件。步骤组件可以根据其内容具有不同的高度。步骤组件加载无需更改路由

工具组件的结构如下所示:

  • 工具组件
    • 步骤-组件 1
    • ....
    • 步骤-组件 X

工具组件负责不同步骤组件之间的切换。

问题

我遇到的问题是,当加载其中一个高度较大的步骤组件时,我会向下滚动到页面底部(实际上是应用程序内容滚动),然后加载另一个具有相同高度的组件,我的滚动位置保持在同一个地方。发生这种情况是因为滚动出现在“app-content”容器级别(正是我想要的位置)。

html angular scroll scroll-position
2个回答
1
投票

最后,我实现了以下解决方案。

我创建了服务 app-scroll.service ,如下所示:

@Injectable({
  providedIn: 'root'
})
export class AppScrollService {

  appComponentScrollToContainerId = 'appComponentScrollToContainerId';
  constructor() { }

  scrollToTop(){
    const container = document.getElementById(this.appComponentScrollToContainerId);
    if(!container){
      throw new Error('Scroll container was not found');
    }
    container.scroll(0, 0);
  }
}

然后我将它注入到 app.component 中,并用它来设置我想要滚动的滚动容器 ID:

<div>
  <div class="app-header">
    <app-header></app-header>
  </div>

  <div class="app-content" [id]="appScrollService.appComponentScrollToContainerId">
    <router-outlet></router-outlet>

    <div class="app-footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

然后,我会在滚动出现问题的地方注入此服务,并在需要时调用它。

如果有需要,也可以在路线更改事件时调用。

如果有人知道更好的解决方案,请告诉我:)


0
投票
    <div class="app-header">
        <app-header></app-header>
    </div>

    <div class="app-content" #content>
        <router-outlet></router-outlet>

        <div class="app-footer">
            <app-footer></app-footer>
        </div>
    </div>


@ViewChild('content') content: ElementRef;

constructor(private router: Router) {

    this.router.events.subscribe((event: RouterEvent) => {

        if (event instanceof NavigationEnd) {
            this.content.nativeElement.scrollIntoView();
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.