Reputation: 86740
I have tried autoscroll="false"
on the router-outlet
but does't seem to work, is there any default method
of angular2 for doing the same without using any third party library?
Upvotes: 4
Views: 12014
Reputation: 1032
Just figured it out. It can be used as smooth scroller to precised ID or instant scroller in order to fix top position.
Component that route is driven to:
ngAfterViewInit(): void {
this.commonService.scrollTo('header', BEHAVIOR.auto)
}
Service:
scrollTo(element: string, behavior: BEHAVIOR): void {
(document.getElementById(element) as HTMLElement).scrollIntoView({behavior: behavior, block: "start", inline: "nearest"});
}
Enum:
export enum BEHAVIOR {
smooth = 'smooth',
auto = 'auto'
}
Upvotes: 0
Reputation: 86740
found answer here https://stackoverflow.com/a/39601987/5043867
we can subscribe to the route change event and scroll to the top with something in the lines of
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
document.body.scrollTop = 0;
});
}
Update -
In Angular v6+ there is a new method scrollPositionRestoration
introduced. for more info read out here
Upvotes: 7
Reputation: 1158
Angular lately introduced a new feature, inside angular routing module make changes like below
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'top'
})],
Upvotes: 4
Reputation: 2560
here is a more neat way to do it:
this.router.events.subscribe((ev:any) => {
if (ev instanceof NavigationEnd) {
window.scrollTo(0, 0);
}
});
You could do this in your router configuration. This is likely to be the norm in future versions as suggested here.
RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
Upvotes: 8