I'm trying to scroll to specific Section in Angular using Fragment routes:
I assumed that I must declare Extra options in my app.routes.ts
import { Routes , ExtraOptions} from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import { NotFoundComponent } from './not-found/not-found.component';
export const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'home', component: HomeComponent},
{path: 'contact', component: ContactComponent},
{path: '**', component: NotFoundComponent}
];
export const routerOptions: ExtraOptions = {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
};
But I have no idea of where to import routerOptions in my app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideClientHydration()]
};
I assumed it works something like this because in the documentation is not clear, any Ideas?
Use additional parameters of provideRouter
, like:
provideRouter(ROUTES, withRouterConfig({...}), withInMemoryScrolling({...}), withComponentInputBinding())
Unfortunately, the docs give no clues what functions you can use there :-(
https://angular.io/api/router/provideRouter
The docs do indeed give a clue, albeit not explicitly.
To do this in Angular 18, instead of declaring the routerOptions
variable in the app.routes.ts
, you add a second argument to ProvideRouter()
in app.config.ts
. The ProvideRouter API Docs specifies that this second argument is an array of RouterFeatures
(you can find the list of possible router features here). For each router feature you want to add, you call a function and pass the configuration state for the feature. To achieve what you're trying to do, this is how to do so, in app.config.ts
:
import { withInMemoryScrolling } from '@angular/router';
export const appConfig: ApplicationConfig = {
providers: [
...
provideRouter(
routes,
withInMemoryScrolling({
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled'
})
),
...
};
Here's the withInMemoryFunction()
docs for you reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With