Search code examples
angularscrollangular-router

Scroll Issue on Navigating to new Route


When I navigate to a new route from my existing route, my new page does not opens at top.

I have already tried many options. This is one of the solution I found, but it didnt work for me.

export class AppComponent implements OnInit { 

    constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
      }

      ngOnInit() {
        this.router.events.subscribe((evt) => {
          if (!(evt instanceof NavigationEnd)) {
            return;
          }
          console.log(evt)
          window.scrollTo(0, 0);
          this.changeDetect.detectChanges();
        });
      }
    }

Any suggestions?


Solution

  • I tried different solution this worked for me

    export class AppComponent implements OnInit {
    
    
      constructor(private router: Router, private changeDetect: ChangeDetectorRef) {
      }
    
      ngOnInit() {
        this.router.events.subscribe((evt) => {
          if (!(evt instanceof NavigationEnd)) {
            return;
          }
          // Change height:100% into auto
          $('body').css('height', 'auto');
          // Successfully scroll back to top
          $('body').scrollTop(0);
          // Remove javascript added styles
          $('body').css('height', '');
          this.changeDetect.detectChanges();
        });
    
      }
    }