Autoscroll in Angular 2

update

Currently there is no automatic way.

See also Angular 2 typescript error when using subscribe function on new router (rc 1)

See also https://github.com/angular/angular/issues/6595#issuecomment-244232725

class MyAppComponent {
  constructor(router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          // you can use DomAdapter
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }
}

update

In the new router V3-beta.2 you can pass a fragment with router links and router navigation

<a [routerLink]="..." fragment="top">

it should scroll to it but also adds #top to the URL (not tested myself yet)

Update

Original

There is an open issue covering this https://github.com/angular/angular/issues/6595

A workaround (mentioned in https://github.com/angular/angular/issues/6946)

Inject the router, subscribe to route changes and invoke the scroll to top:

>= RC.x

router.changes.subscribe() => {
  window.scrollTo(0, 0);
});

beta

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

Leave a Comment