Angular 2 中的自动滚动

新手上路,请多包涵

我在使用 Angular 2 时遇到一个问题,即从一条路线更改为另一条路线不会自动滚动到新视图的顶部。我意识到 Angular 1 允许将 autoscroll 属性添加到 HTML 元素,而其他人提出了一些简单的 javascript(例如 window.scroll(0, 0) )来强制视图滚动到加载时顶部。

但是,我不确定如何使用 Angular 2 来实现这一点。有谁知道如何实现这一点?

原文由 Chris Ryan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 723
2 个回答

更新

目前没有自动方式。

另请参阅 在新路由器上使用订阅功能时出现 Angular 2 typescript 错误(rc 1)

另见 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); }
>         }
>       }
>     });
>   }
> }
>
> ```

**更新**

在新路由器 V3-beta.2 中,您可以传递带有路由器链接和路由器导航的片段


它应该滚动到它,但也会添加 `#top` 到 URL(我自己还没有测试)

**更新**

**原来的**

有一个涵盖此 [https://github.com/angular/angular/issues/6595](https://github.com/angular/angular/issues/6595) 的未决问题

解决方法(在 [https://github.com/angular/angular/issues/6946](https://github.com/angular/angular/issues/6946) 中提到)

注入路由器,订阅路由更改并调用滚动到顶部:

**>= RC.x**

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


**贝塔**

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

”`

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

你能在这里看到吗: https ://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#events-anchor ,你必须使用“router.events.subscribe”因为角度 2.0.0

因此,自动滚动到所有页面顶部的一个很好的解决方案是拥有一个像这样的 AppComponent:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
    constructor(private router: Router) {
        router.events.subscribe((val) => {
            if (val instanceof NavigationEnd){
                window.scrollTo(0,0);
            }
        });
    }
}

原文由 Thierry 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题