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.
2 Answers
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>
11 Comments
לבני מלכה
do you import this to your app
import { Router } from '@angular/router';ruby
I have imported router and no error been seen in console
לבני מלכה
import { Router ,NavigationEnd} from '@angular/router';ssougnez
Try and put the
window.scrollTo in a setTimeout(() => ...)ruby
import { Router, ActivatedRoute,NavigationEnd } from '@angular/router';
|
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