Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...