Angular 2滚动到路线更改顶部 [英] Angular 2 Scroll to top on Route Change

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

问题描述

在我的Angular 2应用程序中,当我向下滚动页面并单击页面底部的链接时,它的确更改了路线并带我进入下一页,但没有滚动到页面顶部.结果,如果第一页很长而第二页的内容很少,则给人的印象是第二页缺少内容.由于只有在用户滚动到页面顶部时内容才可见.

In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.

我可以在组件的ngInit中将窗口滚动到页面顶部,但是,有没有更好的解决方案可以自动处理应用程序中的所有路由呢?

I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?

推荐答案

您可以在主要组件上注册路由更改侦听器,然后滚动到路由更改的顶部.

You can register a route change listener on your main component and scroll to top on route changes.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}

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

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