Ora

How to Create App Routing in Angular?

Published in Angular Routing 6 mins read

Creating app routing in Angular involves defining navigation paths that map to specific components, allowing users to navigate between different views in your single-page application. This essential feature enables a dynamic user experience without full page reloads.

Understanding Angular Routing

Angular's Router module facilitates navigation, letting you map URL paths to components and manage state transitions. It's crucial for building complex applications with multiple views, ensuring a smooth and intuitive user journey. The router works by interpreting the browser's URL and displaying the corresponding component's view within a designated area, typically defined by the <router-outlet> directive.

Setting Up App Routing in Angular

The process of creating app routing generally involves several steps, from generating necessary modules and components to defining the routes and implementing navigation.

Step 1: Generate the Angular Routing Module

When you create a new Angular project, you can opt to include routing from the start by using the --routing flag:

ng new my-angular-app --routing

If you didn't include routing initially or need to add it to an existing module, you can generate a dedicated routing module (e.g., AppRoutingModule). This module is where you'll define all your application's routes.

ng generate module app-routing --flat --module=app

This command creates src/app/app-routing.module.ts and imports it into app.module.ts. The app-routing.module.ts typically looks like this:

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

const routes: Routes = []; // This is where your routes will be defined

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

Step 2: Create Components for Routing

Before you can define routes, you need components for the router to navigate to. Each component will represent a different view or page in your application.

For instance, to create a HomeComponent and a DetailsComponent, you would run the following commands:

ng generate component Home
ng generate component Details

The DetailsComponent is a common requirement for displaying specific information, and its creation follows the same pattern. As an example, the command to create the DetailsComponent is:

ng generate component Details

Step 3: Define Routes in app-routing.module.ts

Now, you will configure your routes by adding objects to the Routes array within app-routing.module.ts. Each route object typically specifies a path (the URL segment) and the component that should be displayed when that path is active.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DetailsComponent } from './details/details.component'; // Import your DetailsComponent
import { AboutComponent } from './about/about.component'; // Assuming you create another component

const routes: Routes = [
  { path: 'home', component: HomeComponent }, // Route for the Home component
  { path: 'details', component: DetailsComponent }, // Route for the Details component
  { path: 'about', component: AboutComponent }, // Route for the About component
  { path: '', redirectTo: '/home', pathMatch: 'full' }, // Default route
  { path: '**', redirectTo: '/home' } // Wildcard route for unmatched paths
];

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

In the example above:

  • { path: 'home', component: HomeComponent } maps the /home URL to the HomeComponent.
  • { path: 'details', component: DetailsComponent } maps the /details URL to the DetailsComponent. This demonstrates how to add a route to a newly created component.
  • { path: '', redirectTo: '/home', pathMatch: 'full' } makes /home the default route when the application loads. pathMatch: 'full' is important to ensure the redirect only happens when the path is exactly empty.
  • { path: '**', redirectTo: '/home' } is a wildcard route that redirects any undefined paths to /home, preventing 404 errors.

Step 4: Configure the RouterOutlet

The RouterOutlet acts as a placeholder where Angular dynamically loads components based on the current router state. You place it in your root component's template (app.component.html).

<!-- app.component.html -->
<nav>
  <ul>
    <li><a routerLink="/home">Home</a></li>
    <li><a routerLink="/details">Details</a></li>
    <li><a routerLink="/about">About</a></li>
  </ul>
</nav>

<main>
  <router-outlet></router-outlet> <!-- The router-outlet displays the routed components -->
</main>

Step 5: Create Navigation Links

To allow users to navigate between routes, use the routerLink directive on anchor tags. The routerLink directive tells the Angular router where to navigate when the user clicks the link.

<!-- app.component.html -->
<nav>
  <ul>
    <li><a routerLink="/home" routerLinkActive="active-link">Home</a></li>
    <li><a routerLink="/details" routerLinkActive="active-link">Details</a></li>
    <li><a routerLink="/about" routerLinkActive="active-link">About</a></li>
  </ul>
</nav>

The routerLinkActive directive adds a CSS class (e.g., active-link) to the active link, which can be styled to highlight the current page.

Key Concepts and Advanced Routing

Angular routing offers powerful features for more complex navigation scenarios.

Route Parameters

You can pass data through the URL using route parameters. For example, to view details of a specific item:

const routes: Routes = [
  { path: 'products/:id', component: ProductDetailComponent },
];

You can then access the id parameter in your ProductDetailComponent using the ActivatedRoute service:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({...})
export class ProductDetailComponent implements OnInit {
  productId: string | null = null;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.productId = params.get('id');
      // Fetch product details based on productId
    });
  }
}

Child Routes (Nested Routes)

For components with internal navigable sections, you can define child routes. These are routes that are relative to a parent route.

const routes: Routes = [
  {
    path: 'admin',
    component: AdminDashboardComponent,
    children: [
      { path: '', redirectTo: 'overview', pathMatch: 'full' },
      { path: 'overview', component: AdminOverviewComponent },
      { path: 'users', component: AdminUsersComponent }
    ]
  }
];

The AdminDashboardComponent would then have its own <router-outlet> to display AdminOverviewComponent or AdminUsersComponent.

Lazy Loading Modules

For performance optimization, you can lazy-load modules, meaning they are only loaded when the user navigates to their associated routes. This significantly reduces the initial bundle size of your application.

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  }
];

Route Guards

Route guards are interfaces that can be implemented to control navigation to, from, or through a route. They are useful for scenarios like authentication checks or confirming user actions before leaving a page.

  • CanActivate: Controls if a route can be activated.
  • CanLoad: Controls if a feature module can be lazy-loaded.
  • CanDeactivate: Controls if a user can exit a route.

Common Routing Properties

Property Description Example
path The URL segment for the route. 'home', 'products/:id', '' (default)
component The component to display for this route. HomeComponent
redirectTo URL to redirect to when this path is matched. '/home', '/login'
pathMatch Determines how the router matches the path (e.g., 'full', 'prefix'). pathMatch: 'full' (matches the entire URL path)
children An array of child Routes for nested routing. children: [{ path: 'profile', component: ProfileComponent }]
loadChildren For lazy loading modules, specifies the module to load. loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
canActivate An array of guards to check before activating the route. canActivate: [AuthGuard]

By understanding these steps and concepts, you can effectively implement app routing in your Angular applications, providing a robust and user-friendly navigation experience.