Navigating the Application: Route Configuration with RouterModule

Learn to configure routing in your Angular application using RouterModule. Discover the difference between forRoot() for the main app and forChild() for feature modules.

🗺️

Welcome! Let's set up routing in an Angular app from scratch.

/* Let's define some routes... */

RouterModule.forRoot(): The Main Switchboard

The `RouterModule.forRoot()` method is used to configure the routes for the entire application. It should only be called once, in the root `AppRoutingModule`. This method provides the necessary router services and directives for the application to work.

RouterModule.forChild(): The Branch Lines

The `RouterModule.forChild()` method is used to configure routes for feature modules. Unlike `forRoot()`, `forChild()` does not re-provide the router services. It registers additional routes with the router, making it ideal for lazy-loaded modules.

RouterOutlet: The Viewport

The `<router-outlet>` is a directive that acts as a placeholder. Angular dynamically fills this placeholder with the component that corresponds to the current router state. You typically place it in your root `AppComponent` template.

RouterLink: The Navigational Trigger

The `routerLink` directive provides a declarative way to navigate between routes. Instead of using `href`, you bind `routerLink` to a string or an array representing the path. This prevents full page reloads and uses the router's navigation mechanism.

Practice Zone


Interactive Test 1: Match the Method

Drag the `RouterModule` method to the module where it belongs.

Arrastra en el orden correspondiente.


Arrastra las opciones:

forRoot()
forChild()

Completa el código:

AppRoutingModule______
FeatureRoutingModule______
Unlock with Premium

Interactive Test 2: Build the Module

Rellena los huecos en cada casilla.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [...];

@NgModule({
  imports: [RouterModule.(routes)],
  exports: []
}) 
export class AppRoutingModule {}
Unlock with Premium

Practice Example: Define Routes

Define routes for a 'home' path and a 'users/:id' path. The second path should load a `UserProfileComponent`.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

import { Routes } from '@angular/router'; const appRoutes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'users/:id', component: UserProfileComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' } ];
Unlock with Premium

Knowledge Check

Why should you only use `forRoot()` once in your application?


Unlock with Premium

Routing in Practice

Good routing architecture is key to a scalable Angular application. Let's look at two advanced concepts: lazy loading and route guards.


1. Lazy Loading Feature Modules

For large applications, you don't want to load all modules at startup. Lazy loading fetches a module only when the user navigates to one of its routes. This is done using `loadChildren` in your route configuration.

// In AppRoutingModule
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
  }
];

2. Protecting Routes with Guards

Route guards are services that implement interfaces like `CanActivate` to control access to a route. You can use them to check if a user is logged in, has certain permissions, or to prevent a user from leaving a page with unsaved changes.

// In your route configuration
{
  path: 'Dashboard',
  component: DashboardComponent,
  canActivate: [AuthGuard] // AuthGuard checks for a valid session
}

Practical Takeaway: Use `forChild` and lazy loading to keep your application modular and performant. Use route guards to create robust, secure navigation flows.

Routing Glossary

Routes
An array of route configuration objects that define the application's navigation paths.
RouterModule
The Angular module that provides the necessary service providers and directives for navigating among views.
routerLink
A directive for binding a clickable HTML element to a route. Clicking an element with a `routerLink` directive that is bound to a string or a link parameters array, navigates to a route.
router-outlet
A directive that acts as a placeholder that Angular dynamically fills based on the current router state.
Route Guard
An interface that a class can implement to control access to a route. Examples include `CanActivate` and `CanDeactivate`.