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?
Asked
Active
Viewed 1.2k times
4

Pardeep Jain
- 84,110
- 37
- 165
- 215
-
2Possible duplicate of [Angular 2 Scroll to top on Route Change](http://stackoverflow.com/questions/39601026/angular-2-scroll-to-top-on-route-change) – Mark E. Haase Dec 30 '16 at 03:19
5 Answers
8
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'})

Hamzeen Hameem
- 2,360
- 1
- 27
- 28
7
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

Pardeep Jain
- 84,110
- 37
- 165
- 215
-
I wish there was an easier way - instead of having the code in the UI in one place it is now in the component code – Rodney Nov 06 '16 at 09:08
-
This is also an easier way I think we have to code once in the main app component – Pardeep Jain Nov 06 '16 at 11:34
-
@Pradeep Jain : This works fine if I change from one route to another however it dosen't scroll to top on param change on same route, I added this service on this._route.params.subscribe event still it remains at same position – Mr X Sep 10 '18 at 21:32
-
yes because for the same route this event will not trigger ,so in that case you need to change your logic depending on the changes of params too – Pardeep Jain Sep 13 '18 at 09:57
4
Angular lately introduced a new feature, inside angular routing module make changes like below
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'top'
})],

Pran R.V
- 1,015
- 12
- 21
0
Just figured it out. It can be used as smooth scroller to precised ID or instant scroller in order to fix top position.
Component that route is driven to:
ngAfterViewInit(): void {
this.commonService.scrollTo('header', BEHAVIOR.auto)
}
Service:
scrollTo(element: string, behavior: BEHAVIOR): void {
(document.getElementById(element) as HTMLElement).scrollIntoView({behavior: behavior, block: "start", inline: "nearest"});
}
Enum:
export enum BEHAVIOR {
smooth = 'smooth',
auto = 'auto'
}

Uland Nimblehoof
- 862
- 17
- 38
-3
-
1will you please elaborate your answer bit more, btw thanks for answer :) – Pardeep Jain Oct 08 '16 at 12:04