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. Can anyone help me to solve this issue so that when I change the router my view always stay at the top.
Thanks in advance.
There some solutions, make sure to check them all :)
The router outlet will emit the activate
event any time a new component is being instantiated, so we could use (activate)
to scroll (for example) to the top:
app.component.html
<router-outlet (activate)="onActivate($event)" ></router-outlet>
app.component.ts
onActivate(event) {
window.scroll(0,0);
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}
or using this answer to smooth scroll
onActivate(event) {
let scrollToTop = window.setInterval(() => {
let pos = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
If you wish to be selective, say not every component should trigger the scrolling, you can check it:
onActivate(e) {
if (e.constructor.name)==="login"{ // for example
window.scroll(0,0);
}
}
{ scrollPositionRestoration: 'enabled' }
on eagerly loaded modules and it will be applied to all routes:
RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
It will also do the smooth scrolling. However this has the inconvenient for doing it on every routing.
query(':enter, :leave', style({ position: 'fixed' }), { optional: true }),
its working . Thanks for your answer. you save a lot of time for me
scroll events on
window
object are not working in angular 5. Any guesses why?@SahilBabbar, Check the body css, overflow:hiden ? what is its height?
A real hero here. Saved possible hours of frustration. Thank you!
@AnjanaSilva, thank you for the positive comment! I am very glad that it could help you :)