Angular 2 Scroll to top on Route Change

angular 7 scroll to top
angular 6 scroll to top on click
angular 6 scroll to top of page
angular 7 scroll to top on click
angular scroll to top button
angular 2 scroll to top of div
angular 4 scroll to top on click
angular 4 scroll to top of page

In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.

I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?

You can register a route change listener on your main component and scroll to top on route changes.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}

Angular 5 Scroll to top on every Route click, The router outlet will emit the activate event any time a new component is being instantiated, See my answer on Angular 2 Scroll to top on Route Change. By default, Angular doesn't scroll to the top of the page when you're navigating to another page. Here is a quick tip on how to implement scrolling. Implement a scroll service. At first, create a new service called ScrollTopService. On a server side (Angular Universal) we don't need this "hack" so it's limited only to a browser. scrolltop

Angular 6.1 and later:

Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:

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

Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 8.2), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.

You can see more details about this feature and how to customize this behavior in the official docs.

Angular 6.0 and earlier:

While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.

The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.

If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}

Changing route doesn't scroll to top in the new page · Issue #7791 , You will end up at exactly the same scroll position at which you were been before opening issue details page. It will be very cool if angular2 router  Angular 2 Scroll to top on Route Change Many of us encounter with a problem of side scroll bar is not being on the top on routing or while navigating to other page. This problem is solved just by using window.scrollTo(0,0);

From Angular 6.1, you can now avoid the hassle and pass extraOptions to your RouterModule.forRoot() as a second parameter and can specify scrollPositionRestoration: enabled to tell Angular to scroll to top whenever the route changes.

By default you will find this in 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 Official Docs

Angular 6 – Add scroll to top when route changes, Angular 6 – Add scroll to top when route changes. Posted on 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. When navigating from one route to another then scrolling down a bit and navigate back to the previous route, the page remains at the same scroll position. Current behavior Navigate from one view to another then scroll down a bit and navi

You can write this more succinctly by taking advantage of the observable filter method:

this.router.events.filter(event => event instanceof NavigationEnd).subscribe(() => {
      this.window.scrollTo(0, 0);
});

If you're having issues scrolling to the top when using the Angular Material 2 sidenav this will help. The window or document body won't have the scrollbar so you need to get the sidenav content container and scroll that element, otherwise try scrolling the window as a default.

this.router.events.filter(event => event instanceof NavigationEnd)
  .subscribe(() => {
      const contentContainer = document.querySelector('.mat-sidenav-content') || this.window;
      contentContainer.scrollTo(0, 0);
});

Also, the Angular CDK v6.x has a scrolling package now that might help with handling scrolling.

Scroll to the top on Angular route change, js, and Java. So I am a Full Stackish web developer with a strong passion for a beautiful front-end. How to detect a route change in Angular? Ask Question Asked 4 years, Angular 2 Scroll to top on Route Change. 0. Angular 2: Redirect to the right route. 3.

If you have server side rendering, you should be careful not to run the code using windows on the server, where that variable doesn't exist. It would result in code breaking.

export class AppComponent implements OnInit {
  routerSubscription: Subscription;

  constructor(private router: Router,
              @Inject(PLATFORM_ID) private platformId: any) {}

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.routerSubscription = this.router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
          window.scrollTo(0, 0);
        });
    }
  }

  ngOnDestroy() {
    this.routerSubscription.unsubscribe();
  }
}

isPlatformBrowser is a function used to check if the current platform where the app is rendered is a browser or not. We give it the injected platformId.

It it also possible to check for existence of variable windows, to be safe, like this:

if (typeof window != 'undefined')

Scroll to the top on Angular route change, By default Angular doesn't scroll to the top of the page when you're navigating to another page. Here is a quick tip how to implement scrolling. We need to see the top content so we need a way to scroll to top every time a link is clicked or router changes. This StackOverflow answer says it all. So I decided to use the smooth scrolling option and added the option to work with Angular Universal, technically, to not scroll to top when running in the server. Update Router Outlet

Scroll to top on Angular Router navigation - Posts, In a S.P.A. this can easily be solved by scrolling to the top on So combining these 2 essentials gives us: angular-js-route-state-change.ts. I am using angular 5. I have a dashboard where I have few sections with small content and few sections with so large content that I am facing a problem when changing router while going to top. Every time I need to scroll to go to top. Can anyone help me to solve this issue so that when I change the router my view always stay at the top.

Angular, However, by preventing the Browser Window from reacting on route change (​fetch a content overflow with scroll, the scroll reset to top on every route change​. When navigating within our SPA, we want to scroll back to the top of the page whenever the route changes. Users have commented that it is really odd if clicking a link at the foot of the page causes the content to change but leaves you s

ExtraOptions, Properties. A set of configuration options for a router module, provided in the forRoot() method. 'top'- Sets the scroll position to x = 0, y = 0 on all navigation. Keep scroll position when navigating back #10929. relatively easy to just scroll top on any route change, but to scroll to previous scroll position is hard

Comments
  • Since Angular 6.1 we can use { scrollPositionRestoration: 'enabled' } on eagerly loaded modules or just in app.module and it will be applied to all routes. RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
  • Muito obrigado sua solução funcionou perfeitamente para mim :)
  • window.scrollTo(0, 0) is a more concise than document.body.scrollTop = 0;, and more readable IMO.
  • Did anybody noticed, that even after implementing this, issue persists in safari browser of Iphone. any thoughts?
  • @mehaase Looks like your answer is the best one. window.body.scrollTop doesn't work for me on Firefox desktop. So thank you !
  • This worked for me, but it breaks the default "back" button behavior. Going back should remember the previous scroll position.
  • This worked!! Although I added $("body").animate({ scrollTop: 0 }, 1000); rather than window.scrollTo(0, 0) to animate smooth scrolling to top
  • This should go either in the app component directly, or in a single component used in it (and therefore shared by the whole app). For instance, I've included it in a top navigation bar component. You should not included in all your components.
  • You can do that and it will make the code more widely compatible with other, non-browser, platforms. See stackoverflow.com/q/34177221/2858481 for implementation details.
  • This should be the accepted answer, so it does not break forward back behavior.