Angular 5 Scroll to top on every Route click

后端 未结 18 1882
遇见更好的自我
遇见更好的自我 2020-11-29 17:49

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

相关标签:
18条回答
  • 2020-11-29 18:18

    try this

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

    this code supported angular 6<=

    0 讨论(0)
  • 2020-11-29 18:22

    Now there's a built in solution available in Angular 6.1 with scrollPositionRestoration option.

    See my answer on Angular 2 Scroll to top on Route Change.

    0 讨论(0)
  • 2020-11-29 18:22

    You just need to create a function which contains adjustment of scrolling of your screen

    for example

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

    window.scrollTo(xpos, ypos) --> expected parameter.

    0 讨论(0)
  • 2020-11-29 18:22

    For some one who is looking for scroll function just add the function and call when ever needed

    scrollbarTop(){
    
      window.scroll(0,0);
    }
    
    0 讨论(0)
  • 2020-11-29 18:25

    From Angular Version 6+ No need to use window.scroll(0,0)

    For Angular version 6+ from @docs
    Represents options to configure the router.

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

    One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' in

    Example:

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

    And if one requires to manually control the scrolling, No need to use window.scroll(0,0) Instead from Angular V6 common package has introduced 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
    }
    

    Usage is pretty Straightforward Example:

    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]));
    }
    
    0 讨论(0)
  • 2020-11-29 18:25

    I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.

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

    Answer from zurfyx original post

    0 讨论(0)
提交回复
热议问题