Search code examples
javascriptangulartypescriptscrolltopangular-router

Angular 5 Scroll to top on every Route click


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 while going to top. Every time I need to scroll to go to top.

How can I solve this issue so that when I change the router, my view always stay at the top?


Solution

  • @ViewChild('topScroll') topScroll: ElementRef;
    
    ngAfterViewInit()
    {
          interval(1000).pipe(
          switchMap(() => of(this.topScroll)),
          filter(response => response instanceof ElementRef),
          take(1))
          .subscribe((input: ElementRef) => {
               input.nativeElement.scrollTop = 0;
           });
     }
    

    This worked like a charm for me. If you strictly want to follow the angular way.