0

I'm trying to understand Angular's forRoot and forChild static methods.

I have two questions.

1) Are the following code snippets equivalent?

This:

// App Module
const routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent }
];

const routing: ModuleWithProviders = RouterModule.forRoot(routes);

with this:

// App Module:
const routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
];

const routing: ModuleWithProviders = RouterModule.forRoot(routes);

// Dashboard Module:
const routes = [
    { path: 'dashboard', component: DashboardComponent }
];

const routing: ModuleWithProviders = RouterModule.forChild(routes);

2) Do they work on the same object?

As I understand it, the forRoot method is the one that instantiates the router services. It adds the first route. The forChild than adds the second route to the same object.

Is that correct? Are forRoot and forChild working in the end on the same instance?

ruffin
  • 16,507
  • 9
  • 88
  • 138
TheAnonymousModeIT
  • 777
  • 1
  • 6
  • 18
  • 1
    yes for the two questions – julianobrasil Jan 17 '20 at 03:58
  • thx @julianobrasil One more short question: I'm using Ionic in my app. In my imports in AppModule I have: 'IonicModule.forRoot()' withforRoot() I can pass config to the IonicModule. If I do not pass any config I can also write 'IonicModule' without forRoot(). This is also equivalent, is it? – TheAnonymousModeIT Jan 17 '20 at 04:15
  • Usually, you need to call `forRoot()`, because it's the way the module content is being exported. Without calling that function, it can happen that you don't import all the necessary exported stuff (`forRoot()` without any parameters may have sensible defaults). – julianobrasil Jan 17 '20 at 18:52
  • Does this answer your question? [Angular: forRoot/forChild methods usage?](https://stackoverflow.com/questions/51500895/angular-forroot-forchild-methods-usage) – ruffin May 05 '20 at 19:18

1 Answers1

3

Only call RouterModule.forRoot() in the root AppRoutingModule (or the AppModule if that's where you register top-level application routes). In any other module, you must call the RouterModule.forChild method to register additional routes.

https://angular.io/guide/router

Here is the difference between RouterModule.forRoot() and RouterModule.forChild()

RouterModule.forRoot()

  1. Declares the router directives
  2. Manages our route configuration

  3. Register the router service

  4. Used once for the application

RouterModule.forChild()

  1. Declares the router directives
  2. Manages our route configuration
  3. Does not register the router service
  4. Used in feature modules
Jason
  • 48
  • 5