正在寻找滚动问题的良好解决方案:)
我的一般应用程序结构如下所示:
<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>
在内容容器中,我加载工具组件,其中加载不同的其他小步骤组件。步骤组件可以根据其内容具有不同的高度。步骤组件加载无需更改路由。
工具组件的结构如下所示:
工具组件负责不同步骤组件之间的切换。
我遇到的问题是,当加载其中一个高度较大的步骤组件时,我会向下滚动到页面底部(实际上是应用程序内容滚动),然后加载另一个具有相同高度的组件,我的滚动位置保持在同一个地方。发生这种情况是因为滚动出现在“app-content”容器级别(正是我想要的位置)。
最后,我实现了以下解决方案。
我创建了服务 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>
然后,我会在滚动出现问题的地方注入此服务,并在需要时调用它。
如果有需要,也可以在路线更改事件时调用。
如果有人知道更好的解决方案,请告诉我:)
<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();
}
});
}