Routing Fundamentals

Back

Loading concept...

🚀 Angular Routing: Your App’s GPS System

Imagine your Angular app is a big building with many rooms. Routing is like having a magical GPS that instantly teleports you to any room when you ask!


🏠 What is Routing?

Think about how you use Google Maps. You type where you want to go, and it shows you the way. Angular Routing works exactly like that for your app!

When someone visits /products, Angular says: “Ah! You want the Products room!” and shows that page instantly.

Simple Example:

You type: myapp.com/home    → Shows Home Page
You type: myapp.com/about   → Shows About Page
You type: myapp.com/contact → Shows Contact Page

Real Life:

  • Clicking a menu link = Telling GPS where to go
  • The page changing = Arriving at destination
  • Back button = Going back to where you came from

📦 RouterModule: The Magic Box

RouterModule is like the engine of your GPS. Without it, nothing works!

Think of it as a toolbox that Angular needs to understand directions.

How to Use It:

// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home';

export const routes: Routes = [
  { path: 'home', component: HomeComponent }
];
// app.config.ts
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig = {
  providers: [provideRouter(routes)]
};

That’s it! You just told Angular: “When someone goes to /home, show the HomeComponent!”


🗺️ Route Configuration: Drawing the Map

Route configuration is like drawing a map of all the rooms in your building.

graph TD A["Your App"] --> B["/home"] A --> C["/products"] A --> D["/about"] A --> E["/contact"] B --> F["HomeComponent"] C --> G["ProductsComponent"] D --> H["AboutComponent"] E --> I["ContactComponent"]

Complete Example:

export const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'products', component: ProductsComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: NotFoundComponent }
];

What Each Part Means:

Part Meaning
path: '' When URL is just / (nothing after)
redirectTo Automatically go somewhere else
pathMatch: 'full' Match the whole path exactly
path: '**' Any path not listed (404 page)

🎯 Route Parameters: Room Numbers

What if you have 1000 products? You can’t create 1000 routes!

Route parameters are like room numbers. Instead of:

  • /product-1
  • /product-2
  • /product-3 … ❌ Crazy!

You do:

  • /products/:id ✅ Smart!

Setting Up Route Parameters:

// In your routes
{ path: 'products/:id', component: ProductDetailComponent }

The :id is a placeholder. It can be anything:

  • /products/42 → id = 42
  • /products/shoes → id = “shoes”
  • /products/abc123 → id = “abc123”

Creating Links with Parameters:

<!-- In your template -->
<a [routerLink]="['/products', product.id]">
  View Product
</a>

If product.id = 5, this creates a link to /products/5.


❓ Query Parameters: Extra Instructions

Query parameters are like adding notes to your GPS request.

Instead of just “Take me to the store”, you say “Take me to the store, and remind me to buy milk”.

The Format:

/products?category=shoes&sort=price
         ↑         ↑         ↑
         ?         &         &
     starts it   separates  separates

Adding Query Parameters:

<!-- Method 1: In template -->
<a [routerLink]="['/products']"
   [queryParams]="{category: 'shoes', sort: 'price'}">
  View Shoes
</a>
// Method 2: In code
this.router.navigate(['/products'], {
  queryParams: { category: 'shoes', sort: 'price' }
});

Both create: /products?category=shoes&sort=price


🔍 ActivatedRoute: Reading the Address

ActivatedRoute is like reading the GPS screen to see where you are.

It tells you:

  • What page are you on?
  • What parameters came with it?
  • Any query parameters?

Getting Route Parameters:

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

@Component({...})
export class ProductDetailComponent {
  private route = inject(ActivatedRoute);

  ngOnInit() {
    // Get the :id from /products/:id
    this.route.params.subscribe(params => {
      console.log('Product ID:', params['id']);
    });
  }
}

Getting Query Parameters:

ngOnInit() {
  // Get ?category=shoes&sort=price
  this.route.queryParams.subscribe(params => {
    console.log('Category:', params['category']);
    console.log('Sort by:', params['sort']);
  });
}
graph TD A["URL: /products/42?sort=price"] --> B["ActivatedRoute"] B --> C["params: id = 42"] B --> D["queryParams: sort = price"]

🎁 Component Input Binding: The Easy Way!

Angular 16+ introduced a super easy way to get route data. No more subscribing!

Enable It First:

// app.config.ts
export const appConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding())
  ]
};

Use It Simply:

import { Component, input } from '@angular/core';

@Component({...})
export class ProductDetailComponent {
  // Route parameter :id becomes an input!
  id = input<string>();

  // Query parameter ?category becomes an input!
  category = input<string>();
}

Before (Old Way):

// 😰 Lots of code
ngOnInit() {
  this.route.params.subscribe(params => {
    this.id = params['id'];
  });
}

After (New Way):

// 😊 So simple!
id = input<string>();

🎮 Putting It All Together

Let’s build a simple product app:

// app.routes.ts
export const routes: Routes = [
  { path: '', redirectTo: 'products', pathMatch: 'full' },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailComponent }
];
<!-- product-list.component.html -->
<h1>Our Products</h1>
<div *ngFor="let product of products">
  <a [routerLink]="['/products', product.id]"
     [queryParams]="{ref: 'list'}">
    {{ product.name }}
  </a>
</div>
// product-detail.component.ts
@Component({...})
export class ProductDetailComponent {
  // With Component Input Binding
  id = input<string>();
  ref = input<string>();  // From ?ref=list

  product = computed(() => {
    return this.productService.getById(this.id());
  });
}

🧠 Quick Summary

Concept What It Does Example
RouterModule Enables routing provideRouter(routes)
Route Config Maps URLs to pages { path: 'home', component: HomeComponent }
Route Params Dynamic URL parts /products/:id/products/42
Query Params Extra info in URL ?sort=price&order=asc
ActivatedRoute Reads current route this.route.params
Input Binding Easy param access id = input<string>()

🌟 You Did It!

Now you understand Angular Routing! 🎉

Think of it like this:

  • Routes = The map of your app
  • RouterModule = The GPS engine
  • Parameters = Specific addresses
  • ActivatedRoute = “You are here” on the map
  • Input Binding = The easiest way to read addresses

Next time you click a link in an Angular app, you’ll know exactly what’s happening behind the scenes!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.