在 Angular 2 中自动滚动 [英] Autoscroll in Angular 2
问题描述
我在使用 Angular 2 时遇到一个问题,即从一条路线更改为另一条路线不会自动滚动到新视图的顶部.我意识到 Angular 1 允许将 autoscroll
属性添加到 HTML 元素,而其他人提出了一些简单的 javascript(例如 window.scroll(0, 0)
) 强制视图在加载时滚动到顶部.
但是,我不确定如何使用 Angular 2 实现这一点.有人知道如何实现吗?
更新
目前没有自动方式.
另见 Angular2 在新路由器上使用订阅功能时出现打字稿错误 (rc 1)
另见 https://github.com/angular/angular/issues/6595#issuecomment-244232725
<块引用>class MyAppComponent {构造函数(路由器:路由器){router.events.subscribe(s => {if (s instanceof NavigationEnd) {const tree = router.parseUrl(router.url);如果(树.片段){//你可以使用 DomAdapterconst element = document.querySelector("#" + tree.fragment);如果(元素){ element.scrollIntoView(元素);}}}});}}
更新
在新的路由器 V3-beta.2 中,您可以传递带有路由器链接和路由器导航的片段
它应该滚动到它,但也会将 #top
添加到 URL(尚未我自己测试过)
更新
原创
有一个悬而未决的问题涉及这个https://github.com/angular/angular/issues/6595
解决方法(在 https://github.com/angular/angular/issues/6946 中提到)
注入路由器,订阅路由变化并调用滚动到顶部:
>= RC.x
router.changes.subscribe() =>{window.scrollTo(0, 0);});
测试版
router.events.filter(e => e NavigationEnd 实例).subscribe(() => {window.scrollTo(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.
However, I am not sure how to accomplish this with Angular 2. Does anyone know how to achieve this?
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);
});
这篇关于在 Angular 2 中自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!