0

Is there a way to configure the Angular2 router to jump to the top of the browser window when the user clicks a link?

First exposure to ang2 so pardon the seemingly noobish Q.

We have a simple list of tiles where each tile is a simple product listing, clicking the tile takes the user to the detail page of the said product... all works great.

When the list is longer the browser window is tall and the product page is of equal or longer length, when the user clicks said product the browsers vertical scroll bar stays put...

We could put a hack (eg: Scroll to the top of the page using JavaScript/jQuery?) in there in js to force the browser to scroll up, but it seems this might/should be something the router would do?

John
  • 4,512
  • 8
  • 48
  • 98
  • https://github.com/Nolanus/ng2-page-scroll would handle it, there are other packages you can get to do it as well. Angular2 is just a framework ultimately built on top of JS, I wouldn't say using window.scrollTo is a hack, it's using native functionality of the language. – silentsod Oct 26 '16 at 15:49
  • Check this out: http://stackoverflow.com/questions/39601026/angular-2-scroll-to-top-on-route-change – Guilherme Meireles Oct 26 '16 at 16:12
  • That is a nice solution, thanks. Would be brilliant if this was configurable higher thought too ie in a routing file eg `{ path: 'topic/:id', component: TopicViewComponent, onloadscrolltotop: true },` – John Oct 27 '16 at 13:24

1 Answers1

0

To scroll the page to top on every router url change, add a router event in your app.component.ts (if you lazy load the children) or to the parent component where the routing occurs.

import { Router, Event as RouterEvent, NavigationEnd} from '@angular/router';

constructor(private router:Router){
  router.events.subscribe((event: RouterEvent) => { /* detects route/navigation change*/
       this.scrollToPageTop(event);
   });
}

scrollToPageTop(event: RouterEvent): void { /* scroll to top on each navigation */
        if (event instanceof NavigationEnd) { /* trigger on  navigation ends */
           document.documentElement.scrollTop = 0; /* for IE */
           document.body.scrollTop = 0; /*for chrome */
        }

}
Veena K. Suresh
  • 781
  • 4
  • 15