Angular 5 Scroll to top on every Route click

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

    
    

提交回复
热议问题