在Angular 2中自动滚动 [英] Autoscroll in Angular 2
问题描述
我遇到Angular 2的问题,从一条路线更改为另一条路线不会自动滚动到新视图的顶部。我意识到Angular 1允许将 autoscroll
属性添加到HTML元素中,而其他人则提出了一些简单的javascript(例如窗口) .scroll(0,0)
)强制视图在加载时滚动到顶部。
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.
但是,我不知道如何使用Angular 2完成此任务。有谁知道如何实现这个目标?
However, I am not sure how to accomplish this with Angular 2. Does anyone know how to achieve this?
推荐答案
更新
目前没有自动方式。
另请参阅在新路由器(rc 1)上使用订阅功能时出现Angular 2打字稿错误
另见 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中,您可以传递带路由器链接和路由器导航的片段
In the new router V3-beta.2 you can pass a fragment with router links and router navigation
<a [routerLink]="..." fragment="top">
它应该滚动到它,但也添加 #top
到URL(尚未自我测试)
it should scroll to it but also adds #top
to the URL (not tested myself yet)
更新
原始
有一个未解决的问题 https://github.com/angular/angular/issues/6595
一种解决方法(在 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);
});
这篇关于在Angular 2中自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!