I was surprised that there is no exact answer to question:
What are methods forRoot/forChild made for?
For example in RouterModule:
Router.forRoot(routes)
RouterModule#forRoot
Creates a module with all the router providers and directives. It also optionally sets up an application listener to perform an initial navigation.
While RouterModule#forChild
Creates a module with all the router directives and a provider registering routes.
The first is usually used to create the initial configuration for the Angular app and register the "base" routes while the second is usually used to configure "relative" routes.
Let's say we have an app with routes for:
You could use the mentioned methods like this:
app-routing.module.ts (this is a "real" app, routes differ)
Where the base routes user/
and company/
are registered using RouterModule#forRoot
//...
const routes: Routes = [
{
path: 'user', loadChildren: './user/user.module#userModule'
// this lazy loading is deprecated in favor of
// loadChildren: () => import('./user/user.module').then(m => m.UserModule) }
},
// same deprecation applies here
{ path: 'company', loadChildren: './company/company.module#CompanyModule'},
// same deprecation applies here
{ path: '**', loadChildren: './page-not-found/page-not-found.module#PageNotFoundModule'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
//...
user-routing.module.ts (this is a "real" app, routes differ)
And the relative routes to user/
and company/
are registered using RouterModule#forChild
//...
const routes: Routes = [
{ path: 'list', component: UserComponent},
{ path: 'delete/:id', component: UserDeleteComponent},
{ path: 'register/:id', component: UserRegisterComponent},
];
@NgModule({
imports: [ RouterModule.forChild(routes) ],
exports: [ RouterModule ]
})
//...
And the same would go on for the Company children routes.
forRoot()
Creates a module with all the router providers and directives. It also optionally sets up an application listener to perform an initial navigation.
forChild()
Creates a module with all the router directives and a provider registering routes.
Use forRoot/forChild convention only for shared modules with providers that are going to be imported into both eager and lazy module modules
Avoiding common confusions with modules in Angular
this one is a greate answer What is purpose of using forRoot in NgModule? can give extra information about this topic
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