Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: forRoot/forChild methods usage?

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)
like image 679
Stepan Suvorov Avatar asked Jul 24 '18 14:07

Stepan Suvorov


2 Answers

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:

  1. User
    • Register
    • List
    • Delete
  2. Company
    • Register
    • List
    • Delete

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.

like image 100
lealceldeiro Avatar answered Sep 28 '22 02:09

lealceldeiro


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

like image 21
Muhammed Albarmavi Avatar answered Sep 28 '22 03:09

Muhammed Albarmavi