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

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

问题描述

我正在使用 angular 5.我有一个仪表板,其中很少有内容较小的部分和很少有内容很大的部分,因此在进入顶部时更换路由器时遇到问题.每次我需要滚动到顶部.谁能帮我解决这个问题,这样当我更换路由器时,我的视图始终保持在顶部.

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 are 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 语句中检查它,如下所示:


If you wish to be selective, say not every component should trigger the scrolling, you can check it in an if statement like this:

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, already. 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 在每次单击 Route 时滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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