I'm trying to create a page that has 2 different route.
I'm trying to import the RouterModule in my standalone component, but do get
Type 'ModuleWithProviders' is not assignable to type 'readonly any[] | Type'.
My code
import { CommonModule } from '@angular/common'
import { ChangeDetectionStrategy, Component } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'
export const routes: Routes = [
{
path: 'first',
loadComponent: () => import('./first/first.component').then((m) => m.FirstComponent),
},
{
path: 'second',
loadComponent: () => import('./second/second.component').then((m) => m.SecondComponent),
},
]
@Component({
selector: 'app-home',
standalone: true,
imports: [
CommonModule,
// Router
RouterModule.forChild(routes), // Error > Type 'ModuleWithProviders<RouterModule>' is not assignable to type 'readonly any[] | Type<any>'.
],
template: `<p>home works!</p>`,
styleUrl: './home.component.css',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent {}
Does somebody have an Idea ?
This is a .forChild() as HomeComponent is being imported inside app.module.ts which have the .forRoot()
For what I understand we cannot use the RouterModule.forChild() in a standalone component.
Therefore we need to import it when we initialise our project.
I keep it in my app-routing.ts file for "separation of concerne" purpose.
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'
export const routes: Routes = [
{
path: '',
loadComponent: () => import('./home/home.component').then((m) => m.HomeComponent),
children: [
{
path: 'first',
loadComponent: () => import('./home/first/first.component').then((m) => m.FirstComponent),
},
{
path: 'second',
loadComponent: () =>
import('./home/second/second.component').then((m) => m.SecondComponent),
},
{
path: '**',
redirectTo: 'first',
},
],
},
]
@NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: 'reload',
scrollPositionRestoration: 'disabled',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
Then you import it in your app.component.ts file.
thx sam for your help
Import RouterModule once at the top level and then lazy load any child routes as required:
// app.routes.ts (main routing document)
export const APP_ROUTES: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: APP_PATHS.FEATURE.AUTH,
},
// AUTH
{
path: APP_PATHS.FEATURE.AUTH,
loadChildren: () =>
import('./features/auth/auth.routes').then(
(mod) => mod.AUTH_ROUTES
),
},
// auth.routes.ts
export const AUTH_ROUTES: Routes = [
{
path: '',
component: SplashComponent,
},
{
path: APP_PATHS.SECTION.LOGIN,
component: LoginComponent,
},
{
path: APP_PATHS.SECTION.FORGOT_PASSWORD,
component: ForgotPasswordComponent,
},
{
path: APP_PATHS.SECTION.REGISTER,
component: RegisterComponent,
},
];
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