Navigation

Back

Loading concept...

🚀 Angular Routing Navigation: Your GPS to App Adventures!

The Big Picture: What’s Navigation All About?

Imagine your Angular app is a theme park with different rides (pages). You need a way to:

  • Show the current ride (Router Outlet)
  • Walk to different rides (RouterLink)
  • Know which ride you’re on (RouterLinkActive)
  • Get teleported by a magic button (Programmatic Navigation)

Let’s explore each one!


🎯 Router Outlet: The Magic Display Screen

What Is It?

Think of <router-outlet> as a TV screen in your living room. The TV stays in one place, but the shows (components) keep changing!

<!-- app.component.html -->
<nav>Menu stays here always</nav>

<router-outlet></router-outlet>
<!-- ^ This is the TV screen! -->

<footer>Footer stays here always</footer>

How It Works

  1. You click a link
  2. Angular finds the matching route
  3. The component appears inside the router-outlet
  4. Everything outside (nav, footer) stays the same!
graph TD A["User Clicks Link"] --> B["Angular Checks Routes"] B --> C["Finds Matching Component"] C --> D["Shows in Router Outlet"] D --> E["Page Updates!"]

Real Example

// app.routes.ts
const routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];

When you visit /about, the AboutComponent shows up in the outlet!


đź”— RouterLink: Magic Doors Between Pages

What Is It?

RouterLink is like a magic door that takes you from one page to another. No page reload needed!

Basic Usage

<!-- Instead of this (causes full reload) -->
<a href="/about">About</a>

<!-- Use this (smooth navigation) -->
<a routerLink="/about">About</a>

Different Ways to Use It

Simple string path:

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

Array format (for dynamic paths):

<a [routerLink]="['/products', productId]">
  View Product
</a>
<!-- Creates: /products/123 -->

With query parameters:

<a
  routerLink="/search"
  [queryParams]="{ q: 'shoes', sort: 'price' }">
  Search Shoes
</a>
<!-- Creates: /search?q=shoes&sort=price -->

Why Not Regular Links?

Regular href RouterLink
Full page reload No reload
Slow Super fast
Loses app state Keeps state
Downloads again Uses cache

✨ RouterLinkActive: The “You Are Here” Sign

What Is It?

Ever seen those mall maps with “You Are Here” markers? RouterLinkActive does the same for your navigation!

Basic Usage

<nav>
  <a routerLink="/home"
     routerLinkActive="active-link">
    Home
  </a>

  <a routerLink="/products"
     routerLinkActive="active-link">
    Products
  </a>
</nav>
.active-link {
  color: blue;
  font-weight: bold;
  border-bottom: 2px solid blue;
}

Now when you’re on /products, that link turns blue automatically!

Multiple Classes

You can add multiple classes:

<a routerLink="/about"
   routerLinkActive="active bold highlighted">
  About
</a>

Exact Matching

By default, /products also matches /products/123. To match exactly:

<a routerLink="/"
   routerLinkActive="active"
   [routerLinkActiveOptions]="{ exact: true }">
  Home
</a>
graph TD A["URL Changes"] --> B{Check All Links} B --> C{URL Matches Link?} C -->|Yes| D["Add Active Class"] C -->|No| E["Remove Active Class"]

🎮 Programmatic Navigation: Teleporting with Code

What Is It?

Sometimes you need to navigate after something happens - like after saving a form or after login. That’s programmatic navigation!

The Router Service

First, inject the Router:

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

@Component({...})
export class LoginComponent {
  constructor(private router: Router) {}
}

navigate() Method

// Go to /dashboard
this.router.navigate(['/dashboard']);

// Go to /products/123
this.router.navigate(['/products', 123]);

// With query params
this.router.navigate(['/search'], {
  queryParams: { q: 'shoes' }
});

navigateByUrl() Method

For full URL strings:

this.router.navigateByUrl('/products/123');

// With query params
this.router.navigateByUrl('/search?q=shoes');

Real Example: After Login

async login() {
  const success = await this.authService.login(
    this.email,
    this.password
  );

  if (success) {
    // Teleport to dashboard!
    this.router.navigate(['/dashboard']);
  } else {
    this.error = 'Wrong password!';
  }
}

Real Example: After Saving

saveProduct() {
  this.productService.save(this.product)
    .subscribe(saved => {
      // Go back to list
      this.router.navigate(['/products']);
    });
}

navigate vs navigateByUrl

navigate() navigateByUrl()
Uses array segments Uses string URL
['/a', 'b', 123] '/a/b/123'
Easier for dynamic parts Good for fixed URLs
More flexible Simpler syntax

đź§© Putting It All Together

Here’s a complete mini-app example:

// app.routes.ts
export const routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailComponent },
];
<!-- app.component.html -->
<nav class="navbar">
  <a routerLink="/home"
     routerLinkActive="active"
     [routerLinkActiveOptions]="{ exact: true }">
    🏠 Home
  </a>

  <a routerLink="/products"
     routerLinkActive="active">
    📦 Products
  </a>
</nav>

<main>
  <router-outlet></router-outlet>
</main>
// product-list.component.ts
@Component({...})
export class ProductListComponent {
  constructor(private router: Router) {}

  viewProduct(id: number) {
    this.router.navigate(['/products', id]);
  }
}

🎓 Quick Summary

Feature Purpose Example
Router Outlet Display area for pages <router-outlet>
RouterLink Click-to-navigate links routerLink="/home"
RouterLinkActive Style current link routerLinkActive="active"
Programmatic Navigate via code router.navigate(['/'])

đź’ˇ Pro Tips

  1. Always use RouterLink for navigation links - never href for internal routes

  2. Use exact matching on your home route to prevent it from always being active

  3. Programmatic navigation is perfect for form submissions, auth flows, and conditional redirects

  4. Router Outlet is required - without it, your components have nowhere to appear!


You’re now ready to navigate your Angular apps like a pro! 🎉

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.