页面在角度导航时不滚动到顶部 [英] Page not scrolling to top while navigating in angular

查看:86
本文介绍了页面在角度导航时不滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序路由url中,加载的页面不会自动滚动到顶部。它保留了与前一个屏幕相同的位置。

In my app while routing urls the page which loads is not scrolling to top automatically. It remains the same position as the previous screen.

我在appcomponent中添加了以下代码,但它仍然无效:(

I have added below codes in appcomponent still it doesn't work:(

 <router-outlet (activate)="onActivate($event)" ></router-outlet>
 onActivate(event) {
    window.scroll(0,0);
    window.scrollTo(0,0);

}


 this.router.events.subscribe((event: NavigationEnd) => {
      if(event instanceof NavigationEnd) {
        window.scrollTo(0, 0);
      }
    })

尝试了所有上述代码,但无法实现此目的。

Tried all these above code but not able to achieve this.

屏幕截图

screenshot

推荐答案

在你的app.component.ts中试试这个
$ b

Try this in your app.component.ts

import { Component } from '@angular/core'; 
import { Router, NavigationEnd } from '@angular/router'; 
import { Subscription } from 'rxjs/Rx';

@Component({
    moduleId: module.id, 
    selector: ‘my-app’,
    template: `<router-outlet></router-outlet>`
})

export class AppComponent {
    routerSubscription: Subscription;

    constructor(private router: Router) {}

    ngOnInit() {
        this.routerSubscription = this.router.events
            .filter(event => event instanceof NavigationEnd)
            .subscribe(event => {
                document.body.scrollTop = 0;
            });
    }

    ngOnDestroy() {
        this.routerSubscription.unsubscribe();
    }
}

删除< router-出口>< / router-outlet> 来自app.component.html

remove <router-outlet></router-outlet> from app.component.html

这篇关于页面在角度导航时不滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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