Angular 5 每次点击路线时滚动到顶部

Angular 5 Scroll to top on every Route click

我正在使用 Angular 5. 我有一个仪表板,其中有几个部分内容较小,部分部分内容很大,以至于我在转到顶部时更改路由器时遇到问题。每次我需要滚动到顶部。

如何解决这个问题,以便在更换路由器时,我的视图始终保持在顶部?

有一些解决方案,请确保全部检查:)


选项 1:

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

app.component.html

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

app.component.ts

onActivate(event) {
   // window.scroll(0,0);

   window.scroll({ 
           top: 0, 
           left: 0, 
           behavior: 'smooth' 
    });

    //or document.body.scrollTop = 0;
    //or document.querySelector('body').scrollTo(0,0)
    ...
}

平滑滚动在Safari中实现的不是很好,例如使用this solution实现平滑滚动:

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

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

选项2:

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

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

它也已经可以平滑滚动了。但是这样在每次路由上都做起来很不方便。


选项 3:

另一种解决方案是在路由器动画上进行顶部滚动。在您想要滚动到顶部的每个过渡中添加此内容:

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

这是一个仅在第一次访问每个组件时才滚动到组件顶部的解决方案(如果您需要对每个组件执行不同的操作):

在每个组件中:

export class MyComponent implements OnInit {

firstLoad: boolean = true;

...

ngOnInit() {

  if(this.firstLoad) {
    window.scroll(0,0);
    this.firstLoad = false;
  }
  ...
}

尽管@Vega 提供了您问题的直接答案,但还是存在问题。它破坏了浏览器的 back/forward 按钮。如果您的用户单击浏览器的后退或前进按钮,他们将失去他们的位置并滚动到顶部。如果您的用户必须向下滚动才能到达 link 并决定单击返回却发现滚动条已重置到顶部,这对您的用户来说可能会有点痛苦。

这是我解决问题的方法。

export class AppComponent implements OnInit {
  isPopState = false;

  constructor(private router: Router, private locStrat: LocationStrategy) { }

  ngOnInit(): void {
    this.locStrat.onPopState(() => {
      this.isPopState = true;
    });

    this.router.events.subscribe(event => {
      // Scroll to top if accessing a page, not via browser history stack
      if (event instanceof NavigationEnd && !this.isPopState) {
        window.scrollTo(0, 0);
        this.isPopState = false;
      }

      // Ensures that isPopState is reset
      if (event instanceof NavigationEnd) {
        this.isPopState = false;
      }
    });
  }
}

我一直在寻找解决这个问题的内置解决方案,就像 AngularJS 中那样。但直到那时这个解决方案对我有用,它很简单,并且保留了后退按钮功能。

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

回答来自zurfyx

编辑: 对于 Angular 6+,请使用 Nimesh Nishara Indimagedara 的回答提及:

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

原答案:

如果全部失败,则在顶部(或所需的滚动位置)创建一些空的 HTML 元素(例如:div),模板上的 id="top"(或父模板):

<div id="top"></div>

并且在组件中:

  ngAfterViewInit() {
    // Hack: Scrolls to top of Page after page view initialized
    let top = document.getElementById('top');
    if (top !== null) {
      top.scrollIntoView();
      top = null;
    }
  }

就我而言,我刚刚添加了

window.scroll(0,0);

ngOnInit() 中并且工作正常。

您只需要创建一个包含屏幕滚动调整的函数

例如

window.scroll(0,0) OR window.scrollTo() by passing appropriate parameter.

window.scrollTo(xpos, ypos) --> 预期参数。

现在 Angular 6.1 中有一个内置解决方案,带有 scrollPositionRestoration 选项。

参见my answer on

试试这个:

app.component.ts

import {Component, OnInit, OnDestroy} from '@angular/core';
import {Router, NavigationEnd} from '@angular/router';
import {filter} from 'rxjs/operators';
import {Subscription} from 'rxjs';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
    subscription: Subscription;

    constructor(private router: Router) {
    }

    ngOnInit() {
        this.subscription = this.router.events.pipe(
            filter(event => event instanceof NavigationEnd)
        ).subscribe(() => window.scrollTo(0, 0));
    }

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

export class AppComponent {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
        window.scrollTo(0, 0);
      }
    });
  }

}

如果您在 Angular 6 中遇到此问题,您可以通过将参数 scrollPositionRestoration: 'enabled' 添加到 app-routing.module.ts 的 RouterModule:

来修复它
@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})

组件:订阅所有路由事件而不是在模板中创建一个动作并在 NavigationEnd b/c 上滚动,否则你会在糟糕的导航或阻塞的路线等情况下触发它......这是一个确保知道如果一条路线成功导航到的方式,然后滚动。否则,什么也不做。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  router$: Subscription;

  constructor(private router: Router) {}

  ngOnInit() {
    this.router$ = this.router.events.subscribe(next => this.onRouteUpdated(next));
  }

  ngOnDestroy() {
    if (this.router$ != null) {
      this.router$.unsubscribe();
    }
  }

  private onRouteUpdated(event: any): void {
    if (event instanceof NavigationEnd) {
      this.smoothScrollTop();
    }
  }

  private smoothScrollTop(): void {
    const scrollToTop = window.setInterval(() => {
      const pos: number = window.pageYOffset;
      if (pos > 0) {
          window.scrollTo(0, pos - 20); // how far to scroll on each step
      } else {
          window.clearInterval(scrollToTop);
      }
    }, 16);
  }

}

HTML

<router-outlet></router-outlet>

试试这个

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'top'
  })],
  exports: [RouterModule]
})

此代码支持 angular 6<=

来自 Angular 版本 6+ 无需使用 window.scroll(0,0)

来自@docs 的 Angular 版本 6+
表示配置路由器的选项。

interface ExtraOptions {
  enableTracing?: boolean
  useHash?: boolean
  initialNavigation?: InitialNavigation
  errorHandler?: ErrorHandler
  preloadingStrategy?: any
  onSameUrlNavigation?: 'reload' | 'ignore'
  scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  anchorScrolling?: 'disabled' | 'enabled'
  scrollOffset?: [number, number] | (() => [number, number])
  paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  urlUpdateStrategy?: 'deferred' | 'eager'
  relativeLinkResolution?: 'legacy' | 'corrected'
}

可以在

中使用scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'

示例:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'|'top' 
});

如果需要手动控制滚动,则不需要使用window.scroll(0,0) 从 Angular 开始,V6 通用包引入了 ViewPortScoller.

abstract class ViewportScroller {
  static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
  abstract setOffset(offset: [number, number] | (() => [number, number])): void
  abstract getScrollPosition(): [number, number]
  abstract scrollToPosition(position: [number, number]): void
  abstract scrollToAnchor(anchor: string): void
  abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}

用法非常简单 示例:

import { Router } from '@angular/router';
import {  ViewportScroller } from '@angular/common'; //import
export class RouteService {

  private applicationInitialRoutes: Routes;
  constructor(
    private router: Router;
    private viewPortScroller: ViewportScroller//inject
  )
  {
   this.router.events.pipe(
            filter(event => event instanceof NavigationEnd))
            .subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}

Angular 6.1 及更高版本:

您可以使用 内置解决方案 Angular 6.1+ 中可用的选项 scrollPositionRestoration: 'enabled' 来实现一样。

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})

Angular 6.0 及更早版本:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

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

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}

注意:预期的行为是,当您导航回页面时,它应该保持向下滚动到您单击 link 时的相同位置,但滚动到到达每一页时的顶部。

如果你使用 mat-sidenav 为路由器插座提供一个 id(如果你有父路由器插座和子路由器插座)并在其中使用激活功能 <router-outlet id="main-content" (activate)="onActivate($event)"> 并使用此 'mat-sidenav-content' 查询选择器滚动到顶部 onActivate(event) { document.querySelector("mat-sidenav-content").scrollTo(0, 0); }

只需添加

window.scrollTo({ top: 0 });

ngOnInit()

对于正在寻找滚动功能的人来说,只需添加功能并在需要时调用

scrollbarTop(){

  window.scroll(0,0);
}

None 出于某种原因对我有用:/,所以我在 app.component.html 中的顶部元素添加了一个元素引用,并在 [=14] 中添加了 (activate)=onNavigate($event) =].

<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>

然后我将 child 添加到 app.component.ts 文件的 ElementRef 类型,并在激活 router-outlet 时滚动到它。

export class AppComponent  {
  @ViewChild('topScrollAnchor') topScroll: ElementRef;

  onNavigate(event): any {
    this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
  }
}

这是 stackblitz

中的代码

对我有用的解决方案:

document.getElementsByClassName('layout-content')[0].scrollTo(0, 0);

它在 angular 8、9 和 10 中有效。

只需在 app.module.ts 文件中添加这一行:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled' //scroll to the top
})

我正在使用 Angular 11.1.4,它对我有用

只需添加

 ngAfterViewInit() {
  window.scroll(0,0)
 }