4

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?

Pardeep Jain
  • 78,495
  • 36
  • 155
  • 210
  • 2
    Possible 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

4 Answers4

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
  • 78,495
  • 36
  • 155
  • 210
  • 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 AJ 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
7

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
  • 1,996
  • 1
  • 26
  • 24
2

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

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'top'
  })],
Pran R.V
  • 855
  • 9
  • 18
-3

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

micronyks
  • 52,386
  • 15
  • 100
  • 135