How to scroll to top on route change in Angular with provideRouter?

32 views Asked by At

How do I force the Angular router to navigate to the top of the page on a route change?

When I was using NgModules, I could do this:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'top' })

But in standalone mode I don't see where I can add this configuration to provideRouter.

// app.config.ts
import { ApplicationConfig } from "@angular/core";
import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
  ],
};
1

There are 1 answers

0
Rens Jaspers On BEST ANSWER

Add withInMemoryScrolling({scrollPositionRestoration: "top"}) as a second parameter to provideRouter:

import { ApplicationConfig } from "@angular/core";
import { provideRouter, withInMemoryScrolling } from "@angular/router";
import { routes } from "./app.routes";

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withInMemoryScrolling({
        scrollPositionRestoration: "top",
      })
    ),
  ],
};