在我的Angular 2应用中,当我向下滚动页面并单击页面底部的链接时,它确实会改变路由并将我带到下一页,但它不会滚动到页面顶部。因此,如果第一页很长,第二页内容很少,就会给人一种第二页缺乏内容的印象。因为只有当用户滚动到页面顶部时,内容才可见。

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


当前回答

最好的答案在Angular GitHub的讨论中(更改路由不会滚动到新页面的顶部)。

也许你只希望在根路由器的更改中(而不是在子路由器中)转到top。 因为你可以在f.e.选项卡中使用惰性加载加载路由)

app.component.html

<router-outlet (deactivate)="onDeactivate()"></router-outlet>

app.component.ts

onDeactivate() {
  document.body.scrollTop = 0;
  // Alternatively, you can scroll to top by using this other call:
  // window.scrollTo(0, 0)
}

全部归功于JoniJnm(原文)

其他回答

如果你只是需要滚动页面到顶部,你可以这样做(不是最好的解决方案,但很快)

document.getElementById('elementId').scrollTop = 0;

@Fernando埃切维里亚 太棒了!但是这段代码不能在哈希路由器或惰性路由器中工作。因为它们不会触发位置更改。 可以试试这个:

private lastRouteUrl: string[] = [] ngOnInit(): void { This.router.events.subscribe ((ev) => { const len = this.lastRouteUrl.length if (ev instanceof NavigationEnd) { this.lastRouteUrl.push (ev.url) If (len > 1 && ev。Url === this。lastRouteUrl[len - 2]) { 返回 } 窗口。scrollTo (0, 0) } }) }

您可以在主组件上注册路由更改侦听器,并在路由更改时滚动到顶部。

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)
        });
    }
}

下面在执行时调用它,它为我工作%100

  document.body.scrollTop = 0;

 this.brandCollectionList$.subscribe((response) => {
  document.body.scrollTop = 0;

});

您可以向组件添加AfterViewInit生命周期钩子。

ngAfterViewInit() {
   window.scrollTo(0, 0);
}