在路线更改和新组件加载不起作用后以角度滚动到顶部

Piy*_*ore 6 scroll google-chrome angular

我正在构建一个基本的 Angular 应用程序,我有一些组件,当我进入服务页面时,从我的主页向下滚动,然后返回主页,滚动设置到页面底部。

每次打开组件时,我都想将滚动设置为顶部。

由于我使用的是 angular7,因此我尝试使用路由器中可用的选项,

{scrollPositionRestoration : 'enabled'}

然后

{scrollPositionRestoration : 'top'},

但它不适用于 Chrome、Chrome 移动设备或 Edge。

除此之外,我尝试在路由器上设置一个侦听器并使用 window.scrollTop(0,0),这也不起作用,使用文档变量也没有。

我只想要我的滚动条在顶部。它是如此天真的事情,但它现在让我感到沮丧。

Ser*_*t42 6

scrollPositionRestoration 对我也不起作用。我通过不使用来自 Angular Material 的“mat-drawer”组件和“scrollPositionRestoration: 'enabled'”解决了这个问题。不幸的是,“mat-drawer-content”的滚动位置无法恢复到之前的滚动状态。如果您没有使用 Angular Material,则可能是另一个组件的错误。

如果您想使用“mat-drawer”滚动到顶部,请使用以下命令:

// Navigate to the given route
public navigate (route: string): void {
    this.router.navigateByUrl(route)
    document.getElementsByTagName('mat-drawer-content')[0].scrollTo(0, 0)
}
Run Code Online (Sandbox Code Playgroud)


Piy*_*ore 3

谢谢你弗里多。在我的例子中,我必须将滚动应用于“mat-drawer-content”。奇迹般有效。

由 frido 回答。

Maybe scrolling doesn't happen on the window but on some other element. You have to figure out what the scrollable container in your case is. e.g. I use a MatSidenav where scrolling happens on the mat-sidenav-content and use document.getElementsByTagName('mat-sidenav-content')[0].scrollTo(0, 0) to scroll to the top on router events.