forRoot method
The forRoot
method is used in the root module (typically app.module.ts) of the Angular application to configure services, routes, and other settings that are shared across the entire application. It is responsible for providing services and configuring routes globally. This method is only called once in the root module.
Syntax:
// Root Module (app.module.ts)
@NgModule({
imports: [RouterModule.forRoot(routes)],
})
export class AppRoutingModule{}
Features of forRoot:
- Global Configuration:
forRoot
allows configuration settings to be applied globally across an Angular application. - Singleton Services: Services provided with
forRoot
are instantiated as singletons, ensuring consistency and preventing duplication. - Router Initialization:
forRoot
sets up initial routes and router configurations at the root level of the application. - Avoids Multiple Instances: By using
forRoot
, you prevent the creation of multiple instances of services and configurations throughout the application. - Library Module Convention:
forRoot
provides a convention for configuring and initializing library modules at the root level of an application.
Example: In this example, we’ll create a simple angular application with global routing using forRoot method.
Step 1: Create a new Angular project
ng new myApp
Step 2: Create two components using the below commands.
ng generate component home
ng generate component about
Step 3: Open src/app/app-routing.module.ts and define the routes for the components that we create in previous step.
<!-- home.component.html -->
<h1>This is the Home Page</h1>
<a routerLink="/about">About</a>
<!-- about.component.html -->
<h1>This is the About Page</h1>
<a routerLink="/">Home</a>
<!-- app.component.html -->
<router-outlet></router-outlet>
//app.routes.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
To start the application run the following commands.
ng serve
Output:
forRoot vs. forChild method in Angular
Routing is an important part of any Angular application which makes it important to understand the difference between forRoot and forChild methods provided by the Angular router module. These methods allow us to configure routing within our application. In this article, we’ll understand both of these methods in detail.
Table of Content
- forRoot method
- forChild Method
- Difference Between forRoot and forChild method
- Conclusion:
In Angular, forRoot and forChild methods are used to configure Angular modules. These methods are primarily used in routing modules to set up routes and services.
Contact Us