Chris Ryan Chris Ryan - 6 months ago 678
Javascript Question

Autoscroll in Angular 2

I'm experiencing an issue with Angular 2 where changing from one route to another does not automatically scroll to the top of the new view. I realize that Angular 1 allowed for an "autoscroll" property to be added to an HTML element, and others had come up with some simple javascript (such as window.scroll(0, 0)) to force views to scroll to the top when loaded. However, I am not sure how to accomplish this with Angular 2. Does anyone know how to achieve this? Thanks!

Answer

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.subscribe(() => {
  window.scrollTo(0, 0);
});

Currently there is no automatic way.

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

Comments