Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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),
  ],
};
like image 531
Rens Jaspers Avatar asked Nov 07 '25 06:11

Rens Jaspers


1 Answers

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",
      })
    ),
  ],
};
like image 173
Rens Jaspers Avatar answered Nov 08 '25 21:11

Rens Jaspers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!