window.scrollTo(0,0)和scrollTop = 0不能处理Angular 2路由更改

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

这是一个非常令人沮丧的问题。我完成了我的应用程序,然后是最后一件事。我一直在监听路由器上的更改,并试图让它在更改后自动滚动到顶部。我在Google上尝试了10种不同的解决方案,没有任何效果。我知道它与路由器有关,但我无法弄清楚为什么它不会滚动。这是我目前正在使用的代码。

app.component.ts

this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
  window.scroll(0, 0);
});

app.component.html

<div class="mainbody bgc-white">
  <router-outlet></router-outlet>
</div>

我尝试了几种变体,特别是使用ElementRef抓取router-outlet元素并设置scrollTop = 0,但这也没有效果。也尝试使用document.body,但没有效果。我在这里错过了什么?

angular angular2-routing
2个回答
1
投票

终于能够让这个工作。没有别的东西适合我。

我不得不创建这个滚动服务:https://github.com/angular/angular/blob/master/aio/src/app/shared/scroll.service.ts

然后将其注入我想要自动滚动到顶部的每个单独页面,然后在页面中调用它。

ngAfterViewInit() {
  [your scroll service].scrollToTop();
}

还必须在我的路由器插座周围的div上放置这个id(这是服务使用的),而不是身体。当我瞄准身体标签时,滚动没有做任何事情。当我将div定位在路由器插座外面时,它工作正常。

<div id="top-of-page">
  <router-outlet></router-outlet>
</div>

我从BogdanC链接的页面得到了这个解决方案,但不得不修改它以适应我的情况。


0
投票

是的我使用的是Angular 5,并且您使用的相同代码不起作用,所以我使用了以下代码也可以,

this.router.events.subscribe(evt => {
    if (evt instanceof NavigationEnd) {
         document.body.scrollTop = 0; // scroll top to body element
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.