Angular 5 Scroll to top on every Route click

后端 未结 18 1844
遇见更好的自我
遇见更好的自我 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: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();
        }
    }
    

提交回复
热议问题