Introduction

Routing is one of the most important concepts in Angular applications. It allows the user to move between pages without reloading the browser. Instead of traditional server-based page navigation, Angular uses client-side routing, which provides a smooth single-page application experience.

If you are building an application that requires multiple screens like Dashboard, Login, Settings, or User Profile, then routing is essential.

In this article, we will learn routing from the ground level using a simple and understandable example: a small application with three pages:

By the end of this article, you will be able to:

Real-World Scenario

Imagine you are building a small ecommerce website. You want users to:

Routing helps make all this possible without reloading the entire application.

Step 1: Creating Components

We will create three components.

ng generate component home
ng generate component products
ng generate component contact
ng generate component product-details
ng generate component page-not-found

Step 2: Enable Routing During Project Creation

If routing was not enabled during project setup, Angular CLI generates a file named:

app-routing.module.ts

This file is where all routes are configured.

Step 3: Defining the Routes

Open app-routing.module.ts and add the following routes:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ContactComponent } from './contact/contact.component';
import { ProductDetailsComponent } from './product-details/product-details.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'products', component: ProductsComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'products/:id', component: ProductDetailsComponent },
  { path: '**', component: PageNotFoundComponent } 
];

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

Explanation

Step 4: Add Router Outlet

To display components based on routes, place a router-outlet tag inside app.component.html.

<nav>
  <a routerLink="/">Home</a> |
  <a routerLink="/products">Products</a> |
  <a routerLink="/contact">Contact</a>
</nav>

<hr>

<router-outlet></router-outlet>

Angular will load components inside <router-outlet> based on navigation.

How Navigation Works

Using routerLink

<a routerLink="/products">View Products</a>

Using Button With Router Navigation

<button [routerLink]="['/contact']">Contact Us</button>

Programmatic Navigation (Inside TypeScript)

import { Router } from '@angular/router';

constructor(private router: Router) {}

goToHome() {
  this.router.navigate(['/']);
}

Passing Route Parameters

When we click a product, we want the product ID to be shown dynamically.

Inside products.component.html:

<ul>
  <li *ngFor="let product of products">
    <a [routerLink]="['/products', product.id]">{{ product.name }}</a>
  </li>
</ul>

Retrieve parameter inside product-details.component.ts:

import { ActivatedRoute } from '@angular/router';

export class ProductDetailsComponent {
  productId: string | null = null;

  constructor(private route: ActivatedRoute) {
    this.productId = this.route.snapshot.paramMap.get('id');
  }
}

Display in UI:

<h2>Product Details for ID: {{ productId }}</h2>

Workflow Diagram

User Clicks Link
       |
       v
 Angular Router Checks Routes
       |
       |-- Match Found? --> Load Component
       |
       |-- No Match --> Load PageNotFound Component

Route Flowchart

            +---------------------+
            | User Enters Route  |
            +----------+----------+
                       |
                       v
           +---------------------------+
           | Check route in config     |
           +-------------+-------------+
                         |
                         |
          +--------------+--------------+
          |                             |
          v                             v
   Match Found                    No Match Found
          |                             |
          v                             v
Load target component           Show PageNotFound

Common Mistakes and Fixes

MistakeWhy it happensFix
Page does not change when clicking linkMissing router-outletAdd <router-outlet> in main template
Page reloads instead of SPA navigationUsing normal <a href=""> tagReplace with routerLink
Route parameter not detectedWrong syntaxUse /products/:id format

Best Practices

Conclusion

Routing is what transforms Angular into a single-page interactive application. With route configuration, navigation methods, route parameters, and error handling routes, you now have a foundation for building real applications.