Episode 16 of 27

Routing

Set up Angular routing — define routes, create page components, and navigate between views in a single-page app.

Routing

Angular's Router lets you navigate between different views (pages) without reloading the browser. It maps URL paths to components.

Setting Up Routes

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent },
    { path: '**', redirectTo: '' },  // Wildcard — redirect unknown routes
];

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

Router Outlet

<!-- app.component.html -->
<app-header></app-header>

<router-outlet></router-outlet>  <!-- Components render HERE -->

<app-footer></app-footer>

<router-outlet> is the placeholder where the routed component is displayed. When the URL changes, Angular swaps the component inside this outlet.

How It Works

URL: /           → HomeComponent renders in <router-outlet>
URL: /about      → AboutComponent renders in <router-outlet>
URL: /contact    → ContactComponent renders in <router-outlet>
URL: /anything   → Redirects to / (wildcard route)

Route Configuration Options

PropertyPurpose
pathURL path segment
componentComponent to render
redirectToRedirect to another path
pathMatch'full' or 'prefix' — how to match
childrenNested (child) routes
dataStatic data passed to the route

Redirect Route

// Redirect /home to /
{ path: 'home', redirectTo: '', pathMatch: 'full' },

// Catch-all (404)
{ path: '**', component: NotFoundComponent }

Programmatic Navigation

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

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

    onLogin(): void {
        // Navigate to /dashboard after login
        this.router.navigate(['/dashboard']);
    }
}

Key Takeaways

  • Define routes as an array of { path, component } objects
  • <router-outlet> is where the matched component renders
  • Use ** wildcard for 404 or catch-all routes (must be last!)
  • Router.navigate() handles programmatic navigation
  • Routes are defined in AppRoutingModule and imported into the app module