问题
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