Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 scroll to top on route change not working

I am trying to scroll to the top of my page on my angular 2 site when the route changes, I have tried the following, but nothing happens, when I change the route from one page to another, the page is scrolled to where it was on the first page:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

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

What am I doing wrong?

like image 702
user979331 Avatar asked Nov 07 '18 01:11

user979331


Video Answer


1 Answers

The router will emit an event when a new component gets loaded in the <router-outlet> so you can attach an event to it.

So in your component with <router-outlet> use:

<router-outlet (activate)="scrollTop($event)">

and then in the same component where you placed <router-outlet> add the following method:

scrollTop(event) {
  window.scroll(0,0);
}
like image 108
Mac_W Avatar answered Oct 02 '22 21:10

Mac_W