Angular 5 Scroll to top on every Route click

后端 未结 18 1840
遇见更好的自我
遇见更好的自我 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:27

    If you face this problem in Angular 6, you can fix it by adding the parameter scrollPositionRestoration: 'enabled' to app-routing.module.ts 's RouterModule:

    @NgModule({
      imports: [RouterModule.forRoot(routes,{
        scrollPositionRestoration: 'enabled'
      })],
      exports: [RouterModule]
    })
    
    0 讨论(0)
  • 2020-11-29 18:28

    Here is a solution that only scrolls to top of Component if first time visiting for EACH component (in case you need to do something different per component):

    In each Component:

    export class MyComponent implements OnInit {
    
    firstLoad: boolean = true;
    
    ...
    
    ngOnInit() {
    
      if(this.firstLoad) {
        window.scroll(0,0);
        this.firstLoad = false;
      }
      ...
    }
    
    0 讨论(0)
  • 2020-11-29 18:30

    if your using mat-sidenav give an id to the router outlet( if you have a parent and child router outlets) and use activate function in it <router-outlet id="main-content" (activate)="onActivate($event)"> and use this 'mat-sidenav-content' query selector to scroll top onActivate(event) { document.querySelector("mat-sidenav-content").scrollTo(0, 0); }

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

    Try this:

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

    Component: Subscribe to all routing events instead of creating an action in the template and scroll on NavigationEnd b/c otherwise you'll fire this off on bad navs or blocked routes, etc... This is a sure fire way to know that if a route successfully is navigated to, then sooth scroll. Otherwise, do nothing.

    @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>
    
    0 讨论(0)
  • 2020-11-29 18:38

    EDIT: For Angular 6+, please use Nimesh Nishara Indimagedara's answer mentioning:

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

    Original Answer:

    If all fails, then create some empty HTML element (eg: div) at the top (or desired scroll to location) with id="top" on template (or parent template):

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

    And in component:

      ngAfterViewInit() {
        // Hack: Scrolls to top of Page after page view initialized
        let top = document.getElementById('top');
        if (top !== null) {
          top.scrollIntoView();
          top = null;
        }
      }
    
    0 讨论(0)
提交回复
热议问题