How to load routing module in angular 17 for RouterModule.forChild

754 Views Asked by At

I need to covert my Angular 16 project into Angular 17 And I used the routing module for lazy loading in Angular 16 my Angular 16 code was like this

@NgModule({
    declarations: [DashboardComponent],
    imports: [
        CommonModule,
        RouterModule.forChild([
            {
                path: '',
                component: DashboardComponent,
            },
        ]),
    ],
})


I just need this into Angular 17


Thanks in Advance.
2

There are 2 best solutions below

1
BioPhysicist On
const routes: Routes = [{path:'', component: DashboardComponent}];
@NgModule({
    declarations: [DashboardComponent],
    imports: [
        CommonModule,
        RouterModule.forRoot(routes)
        ],
    exports: [RouterModule]    ]
})
export class AppRoutingModule{}

Try this on

0
Nasser HARTI On

According to the documentation : https://angular.dev/guide/ngmodules/lazy-loading

Now, to link childs, You need to go in the routes file (where are the root paths) :

app.routes.ts

And then, link your child (the module child with the children paths inside) to the router as below :

export const routes: Routes = [{
    path: '',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => DashboardModule)
}];

Some explanations :

In this code, I supposed that the name of your module is "DashboardModule".

The keyword "path" gives you the possibility to choose a prefix for all paths in your DashboardModule.

Then, the keyword "loadChildren" is used to connect your child module and the children paths through it.

For all Child modules (with paths indeed) you want to link to the root, you need to add this code fragment in the routes array of the app.routes.ts file.

(ps: pay attention to the order in which you insert the routes, as usual)

Regards,