在我的Angular 2应用中,当我向下滚动页面并单击页面底部的链接时,它确实会改变路由并将我带到下一页,但它不会滚动到页面顶部。因此,如果第一页很长,第二页内容很少,就会给人一种第二页缺乏内容的印象。因为只有当用户滚动到页面顶部时,内容才可见。

我可以滚动窗口到ngInit组件的页面顶部,但是,有没有更好的解决方案,可以自动处理我的应用程序中的所有路由?


当前回答

您可以向组件添加AfterViewInit生命周期钩子。

ngAfterViewInit() {
   window.scrollTo(0, 0);
}

其他回答

window.scrollTo()在Angular 5中不适用,所以我使用了document.body.scrollTop:

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

从Angular 6.1开始,你现在可以避免这种麻烦,将extraOptions作为第二个参数传递给RouterModule.forRoot(),并可以指定scrollPositionRestoration: enabled来告诉Angular当路由发生变化时滚动到顶部。

默认情况下,你会在app-routing.module.ts中找到这个:

const routes: Routes = [
  {
    path: '...'
    component: ...
  },
  ...
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled', // Add options right here
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Angular官方文档

Here's a solution that I've come up with. I paired up the LocationStrategy with the Router events. Using the LocationStrategy to set a boolean to know when a user's currently traversing through the browser history. This way, I don't have to store a bunch of URL and y-scroll data (which doesn't work well anyway, since each data is replaced based on URL). This also solves the edge case when a user decides to hold the back or forward button on a browser and goes back or forward multiple pages rather than just one.

附注:我只测试了最新版本的IE、Chrome、FireFox、Safari和Opera(截至本文)。

希望这能有所帮助。

export class AppComponent implements OnInit {
  isPopState = false;

  constructor(private router: Router, private locStrat: LocationStrategy) { }

  ngOnInit(): void {
    this.locStrat.onPopState(() => {
      this.isPopState = true;
    });

    this.router.events.subscribe(event => {
      // Scroll to top if accessing a page, not via browser history stack
      if (event instanceof NavigationEnd && !this.isPopState) {
        window.scrollTo(0, 0);
        this.isPopState = false;
      }

      // Ensures that isPopState is reset
      if (event instanceof NavigationEnd) {
        this.isPopState = false;
      }
    });
  }
}

您可以向组件添加AfterViewInit生命周期钩子。

ngAfterViewInit() {
   window.scrollTo(0, 0);
}

如果你只是需要滚动页面到顶部,你可以这样做(不是最好的解决方案,但很快)

document.getElementById('elementId').scrollTop = 0;