If my understanding is correct, you are looking to have the page always scroll up when navigating. What is the reason for this behavior? Typically, when a new page or component is loaded, it starts at the top by default.
One approach is to adjust the scroll position restoration setting in your AppModule or AppRoutingModule based on the documentation you provided.
@NgModule({
imports: [
RouterModule.forRoot(routes, { scrollPositionRestoration: 'top' }),
],
exports: [RouterModule],
providers: [ScrollToTopService],
})
'top' - This setting will reset the scroll position to x = 0, y = 0 upon navigation.
Alternatively, you can implement custom scrolling logic using a service and inject it into the module.
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable()
export class ScrollToTopService {
constructor(router: Router) {
router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(() => {
window.scrollTo(0, 0);
});
}
}
Instead of using scrollPositionRestoration, include the following inside your module:
providers: [ScrollToTopService]