Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable ExtraOptions in an Angular 17 without app routing module?

Tags:

angular17

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?

like image 971
MachPlomo Avatar asked Sep 01 '25 23:09

MachPlomo


2 Answers

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

like image 80
Tomasz Śmigielski Avatar answered Sep 03 '25 13:09

Tomasz Śmigielski


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.

like image 28
Koyejo Avatar answered Sep 03 '25 13:09

Koyejo