Angular 5每次单击路线时滚动到顶部 [英] Angular 5 Scroll to top on every Route click

查看:111
本文介绍了Angular 5每次单击路线时滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular5.我有一个仪表板,其中的几个部分内容很少,而几个部分内容太大,以至于在转到顶部时更改路由器时都遇到了问题.每次我需要滚动到顶部时.谁能帮助我解决此问题,以便在我更换路由器时,我的看法始终停留在顶部.

I am using angular 5. I have a dashboard where I have few sections with small content and few sections with so large content that I am facing a problem when changing router while going to top. Every time I need to scroll to go to top. Can anyone help me to solve this issue so that when I change the router my view always stay at the top.

谢谢.

推荐答案

有一些解决方案,请务必全部检查:)

There some solutions, make sure to check them all :)

每当实例化一个新组件时,路由器插座就会发出activate事件,因此我们可以使用(activate)滚动(例如)到顶部:

The router outlet will emit the activate event any time a new component is being instantiated, so we could use (activate) to scroll (for example) to the top:

app.component.html

<router-outlet (activate)="onActivate($event)" ></router-outlet>

app.component.ts

onActivate(event) {
    window.scroll(0,0);
    //or document.body.scrollTop = 0;
    //or document.querySelector('body').scrollTo(0,0)
    ...
}

或使用此答案以平滑滚动

    onActivate(event) {
        let scrollToTop = window.setInterval(() => {
            let pos = window.pageYOffset;
            if (pos > 0) {
                window.scrollTo(0, pos - 20); // how far to scroll on each step
            } else {
                window.clearInterval(scrollToTop);
            }
        }, 16);
    }


如果您希望有所选择,说不是每个组件都应触发滚动,则可以进行检查:


If you wish to be selective, say not every component should trigger the scrolling, you can check it:

onActivate(e) {
    if (e.constructor.name)==="login"{ // for example
            window.scroll(0,0);
    }
}


从Angular6.1开始,我们还可以在热切加载的模块上使用{ scrollPositionRestoration: 'enabled' },它将应用于所有路由:


Since Angular6.1, we can also use { scrollPositionRestoration: 'enabled' } on eagerly loaded modules and it will be applied to all routes:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })

它还将进行平滑滚动.然而,这在每个路由上都具有不便之处.


另一种解决方案是对路由器动画进行顶部滚动.在您要滚动到顶部的每个过渡中添加此代码:

It will also do the smooth scrolling. However this has the inconvenient for doing it on every routing.


An other solution is to do the top scrolling on router animation. Add this in every transition where you want to scroll to the top:

query(':enter, :leave', style({ position: 'fixed' }), { optional: true }),

这篇关于Angular 5每次单击路线时滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆