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