我在使用 Angular 2 时遇到一个问题,即从一条路线更改为另一条路线不会自动滚动到新视图的顶部。我意识到 Angular 1 允许将 autoscroll
属性添加到 HTML 元素,而其他人提出了一些简单的 javascript(例如 window.scroll(0, 0)
)来强制视图滚动到加载时顶部。
但是,我不确定如何使用 Angular 2 来实现这一点。有谁知道如何实现这一点?
原文由 Chris Ryan 发布,翻译遵循 CC BY-SA 4.0 许可协议
我在使用 Angular 2 时遇到一个问题,即从一条路线更改为另一条路线不会自动滚动到新视图的顶部。我意识到 Angular 1 允许将 autoscroll
属性添加到 HTML 元素,而其他人提出了一些简单的 javascript(例如 window.scroll(0, 0)
)来强制视图滚动到加载时顶部。
但是,我不确定如何使用 Angular 2 来实现这一点。有谁知道如何实现这一点?
原文由 Chris Ryan 发布,翻译遵循 CC BY-SA 4.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 许可协议
13 回答13.1k 阅读
7 回答2.2k 阅读
3 回答1.4k 阅读✓ 已解决
6 回答1.4k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
6 回答1.2k 阅读
更新
目前没有自动方式。
另请参阅 在新路由器上使用订阅功能时出现 Angular 2 typescript 错误(rc 1)
另见 https://github.com/angular/angular/issues/6595#issuecomment-244232725
router.changes.subscribe() => { window.scrollTo(0, 0); });
router.events .filter(e => e instanceof NavigationEnd) .subscribe(() => { window.scrollTo(0, 0); });
”`