Reputation: 55
I want to disable scrollPositionRestoration on one page. Let's say I have the following routes in my app-routing.module.ts file...
const appRoutes: Routes = [{ path: 'home', component: myComponent}, { path: 'about', component: myComponent}, ]
and I have my imports as follows...
@NgModule({imports: [RouterModule.forRoot(appRoutes, {
scrollPositionRestoration: 'enabled'
})]
How would I disable the scollPositionRestoration on the 'about' route?
Upvotes: 3
Views: 2080
Reputation: 341
You could not control scrollPositionRestoration
value differently in different routes. This option for root module only. As a result, In your case you should remove it from root module (by default scrollPositionRestoration
value is 'disabled'
) and can control the position of scroll by Router
and ViewportScroller
.
In the app.component
You can listen navigation events like this:
this.router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
// if (..) You can write any logic for moving the scroll to the top or not
this.viewport.scrollToPosition([0, 0]);
}
});
Upvotes: 1
Reputation: 26
Do not use: scrollPositionRestoration: 'enabled'
Reset back to:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
Then use this in your home.component.ts only:
scrollTop() {
window.scroll(0, 0);
}
Then add (click)="scrollTop()"
where you want to execute it.
Upvotes: 1