On route change view doesn't scroll to top in the new page in angular2

回眸只為那壹抹淺笑 提交于 2020-05-27 12:18:06

问题


I have tried autoscroll="false" on the router-outlet but does't seem to work, is there any default method of angular2 for doing the same without using any third party library?


回答1:


found answer here https://stackoverflow.com/a/39601987/5043867

we can subscribe to the route change event and scroll to the top with something in the lines of

ngOnInit() {
    this.router.events.subscribe((evt) => {
        if (!(evt instanceof NavigationEnd)) {
            return;
        }
        document.body.scrollTop = 0;
    });
}

Update -

In Angular v6+ there is a new method scrollPositionRestoration introduced. for more info read out here

  • https://medium.com/@PardeepJain/deep-dive-into-angular-routing-scrolling-to-top-debugging-and-lot-more-a995c08498d3



回答2:


Until Angular 6

here is a more neat way to do it:

this.router.events.subscribe((ev:any) => {
  if (ev instanceof NavigationEnd) {
    window.scrollTo(0, 0);
  }
});

From Angular 6.1

You could do this in your router configuration. This is likely to be the norm in future versions as suggested here.

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})



回答3:


Angular lately introduced a new feature, inside angular routing module make changes like below

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



回答4:


Yes, you can refer to fragments available in Angular2-router.



来源:https://stackoverflow.com/questions/39931650/on-route-change-view-doesnt-scroll-to-top-in-the-new-page-in-angular2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!