Author avatar

Zachary Bennett

forRoot and forChild Static Methods on the Angular Router

Zachary Bennett

  • Sep 11, 2020
  • 6 Min read
  • 65 Views
  • Sep 11, 2020
  • 6 Min read
  • 65 Views
Web Development
Front End Web Development
Angular
Client-side Frameworks

Introduction

Angular is a powerful and opinionated framework. It is a "batteries-included" framework that comes with many powerful libraries and modules baked in so that you can start building your app quickly. One of the features that Angular includes out-of-the-box is the Angular Router. In this guide, you will learn how to use the Angular Router— specifically the forRoot and forChild static methods.

Let's get started!

Angular Router Overview

The Angular Router is a fully-featured routing system that works with the already existing module system within Angular. It allows you to define your app routes while maintaining a good practice of separation of concerns. Pretty much every JavaScript framework has a router available for use in some form or another. Some frameworks, like Angular, optionally include their router inside of new apps that you generate.

To include the router inside of your new app, you simply have to run the following command using the Angular CLI: ng new my-app --routing. This command will generate an app-routing.module.ts file that contains a root-level AppRoutingModule. This is Angular's way of defining where the RouterModule is brought in to your app and where your routes are defined. In the coming sections, you will learn about the forRoot and forChild static methods that are available on the RouterModule itself and how to use them to compose your routes.

Note: The Angular CLI does not let you use the --routing parameter until version 8.1.

The `forRoot` Static Method

The forRoot static method is the method that configures the root routing module for your app. When you call RouterModule.forRoot(routes), you are asking Angular to instantiate an instance of the Router class globally. Just like Angular creates a new base AppModule to import all of your feature modules, it also provides the AppRoutingModule to import all of your child routes.

In the new app that you have created via the Angular CLI, the forRoot method is actually already being used inside of the app-routing.module.ts. In your app, you only want to use the forRoot method once. This is because this method tells Angular to instantiate an instance of the Router class under the hood, and there can be only one router in your app. The forRoot static method is a part of a pattern that ensures that you are using singleton classes. For more about the singleton pattern, check out the wiki.

Simply put, if you use the --routing parameters while creating your app, you have no need to really worry about using the forRoot method because it is already set up for you! In the next section, you'll learn how to use the forChild static method to register child routes with your app router.

Child Routes

The forChild static method constitutes the other side of the forRoot/forChild pattern mentioned above. When you are using the forChild static method, you are basically telling Angular, "There is already a Router instance available in the app so please just register all of these routes with that instance." The forChild method is the method that you will call to register routes throughout your app and you will use it inside of the child, routing modules that you create. The forChild static method is useful because it plays a core part of Angular module functionality by allowing you to maintain separation of concerns within your app. Let's see how you could use this in a real app!

Suppose you want to create a new feature module for user settings in your app and this feature will contain a few routes. Instead of adding these routes into the AppRoutingModule directly, which would eventually become untenable as your app grows, you can maintain separation of concerns within your app by using the forChild method. First, create a new UserSettingsRoutingModule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { NgModule } from  '@angular/core';
import { Routes, RouterModule } from  '@angular/router';

import { UserSettingsComponent } from './user-settings.component';
import { UserProfileComponent } from  './user-profile/user-profile.component';

const  routes:  Routes  = [
    {
        path:  'settings',
        component:  UserSettingsComponent,
        children: [
            {
                path:  'profile',
                component: UserProfileComponent 
            }
        ]
    }
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export  class  UserSettingsRoutingModule { }
typescript

Note the use of the forChild method above. Since you have already used the forRoot method, you'll just want to register your routes to the already instantiated app router.

Now you need to create your UserSettingsModule like this:

1
2
3
4
5
6
7
8
9
10
11
import { NgModule, CommonModule } from  '@angular/core';
import { UserSettingsRoutingModule } from  './user-settings-routing.module';

@NgModule({
    imports: [
        CommonModule,
        UserSettingsRoutingModule
    ],
    // Configure the rest of your module here
})
export class UserSettingsModule { }
typescript

And there you have it! Now all you would need to do is import this UserSettingsModule into your root, AppModule, and your child routes that point to their respective components would be configured within your app.

Conclusion

In this guide, you took a deep dive into the Angular Router. First, you got your bearings through a brief overview of the Router service itself. Then, you learned how the forRoot static method located on the router can be used to initialize the Router service for your app. Wrapping it up, you learned about the forChild static method and how this method allows you to do wire in child routes while maintaining separation of concerns between your modules and components.

I hope that this guide has helped you to understand how the Angular Router static methods forRoot and forChild can help you to create well structured routes within your app. For more information, check out Angular's documentation.

1