Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

forRoot and forChild Static Methods on the Angular Router

Sep 11, 2020 • 6 Minute Read

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.

      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 { }
    

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:

      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 { }
    

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.

Zachary Bennett

Zachary B.

Zach is currently a Lead Software Developer at OpalSoft where he uses tools such as Scala, TypeScript, Python, Docker, Node, and Angular. Zach has a passion for GIS programming along with open-source software. You can view some of his work on GitHub (https://github.com/zbennett10) and Stack Overflow (https://stackoverflow.com/users/6879849/zachary-bennett).

More about this author