1

In my app while routing urls the page which loads is not scrolling to top automatically. It remains the same position as the previous screen.

0

2 Answers 2

0

Try this in your app component:

TS:

import { Router ,NavigationEnd} from '@angular/router';
export class AppComponent{
    constructor(private router: Router) {}

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

HTML:

<router-outlet></router-outlet>
Sign up to request clarification or add additional context in comments.

11 Comments

do you import this to your app import { Router } from '@angular/router';
I have imported router and no error been seen in console
import { Router ,NavigationEnd} from '@angular/router';
Try and put the window.scrollTo in a setTimeout(() => ...)
import { Router, ActivatedRoute,NavigationEnd } from '@angular/router';
|
0

Try this in your app.component.ts

import { Component } from '@angular/core'; 
import { Router, NavigationEnd } from '@angular/router'; 
import { Subscription } from 'rxjs/Rx';

@Component({
    moduleId: module.id, 
    selector: ‘my-app’,
    template: `<router-outlet></router-outlet>`
})

export class AppComponent {
    routerSubscription: Subscription;

    constructor(private router: Router) {}

    ngOnInit() {
        this.routerSubscription = this.router.events
            .filter(event => event instanceof NavigationEnd)
            .subscribe(event => {
                document.body.scrollTop = 0;
            });
    }

    ngOnDestroy() {
        this.routerSubscription.unsubscribe();
    }
}

remove <router-outlet></router-outlet> from app.component.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.