TExcelTAD
Home › Angular › Angular Routing

Angular Routing

A single-page application loads one HTML page and swaps components in and out as the user navigates. The Angular Router maps URLs to components, updates the address bar, supports the back button and can load parts of the app lazily.

1. Define routes

Routes live in app.routes.ts. Each route pairs a path with a component:

ts
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home';
import { About } from './about';
import { NotFound } from './not-found';

export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  { path: 'about', component: About, title: 'About us' },
  { path: 'tasks', loadComponent: () => import('./tasks').then((m) => m.Tasks) },
  { path: 'home', redirectTo: '', pathMatch: 'full' },
  { path: '**', component: NotFound },
];
Property Meaning
path URL segment without leading slash; '' is the root
component Component to show for this URL
loadComponent Lazily load the component's code on first visit
title Sets the browser tab title
redirectTo + pathMatch: 'full' Redirect an exact URL elsewhere
'**' Wildcard — matches anything not matched before; keep it last

The routes are registered once with provideRouter(routes) in app.config.ts (the CLI does this for you).

2. Add an outlet and links

<router-outlet /> marks where the routed component appears. routerLink creates navigation links that don't reload the page, and routerLinkActive adds a class to the link of the current route:

angular · try it yourself
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink, RouterLinkActive],
  template: `
    <nav>
      <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
      <a routerLink="/tasks" routerLinkActive="active">Tasks</a>
      <a routerLink="/about" routerLinkActive="active">About</a>
    </nav>
    <main><router-outlet /></main>
  `,
  styles: `
    nav { display: flex; gap: 16px; padding: 10px 16px; background: #dd0031; }
    nav a { color: #ffd6de; text-decoration: none; }
    nav a.active { color: #fff; font-weight: bold; border-bottom: 2px solid #fff; }
    main { padding: 16px; }
  `,
})
export class App {}

Note: Use routerLink instead of href. A plain href makes the browser reload the whole app; routerLink navigates inside the running app.

3. Navigate from code

Inject the Router to navigate after an action — for example, after saving a form:

angular · try it yourself
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-new-task',
  template: `<button (click)="save()">Save task</button>`,
})
export class NewTask {
  private router = inject(Router);

  async save() {
    // ...save the task...
    const ok = await this.router.navigate(['/tasks'], { queryParams: { created: 1 } });
    console.log('navigated:', ok, this.router.url);
  }
}
navigated: true /tasks?created=1

How route matching works

The router checks routes in order and uses the first one that matches. That's why the '**' wildcard must come last. A simplified matcher in plain TypeScript:

ts · try it yourself
interface Route { path: string; name: string; }

const routes: Route[] = [
  { path: '', name: 'Home' },
  { path: 'tasks', name: 'Tasks' },
  { path: 'tasks/:id', name: 'TaskDetail' },
  { path: '**', name: 'NotFound' },
];

function match(url: string): string {
  const parts = url.split('/').filter(Boolean);
  for (const r of routes) {
    if (r.path === '**') return r.name;
    const rParts = r.path.split('/').filter(Boolean);
    if (rParts.length !== parts.length) continue;
    const params: Record<string, string> = {};
    const ok = rParts.every((seg, i) => {
      if (seg.startsWith(':')) { params[seg.slice(1)] = parts[i]; return true; }
      return seg === parts[i];
    });
    if (ok) return Object.keys(params).length ? `${r.name} ${JSON.stringify(params)}` : r.name;
  }
  return 'no match';
}

for (const url of ['/', '/tasks', '/tasks/42', '/settings']) {
  console.log(url.padEnd(10), '->', match(url));
}
/          -> Home
/tasks     -> Tasks
/tasks/42  -> TaskDetail {"id":"42"}
/settings  -> NotFound

Lazy loading

loadComponent (for one component) and loadChildren (for a whole child route array) split the app into chunks that download only when needed:

ts
{ path: 'admin', loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES) }

Your initial bundle stays small, so the first page appears faster.

Tip: Nested routes use children: [...] and a second <router-outlet /> inside the parent component — great for layouts with a sidebar.

Test yourself

Where does the router render the component for the current URL?

  1. In index.html's <body>
  2. In place of <router-outlet />
  3. In a new browser tab
  4. At the top of every component

Why must the '**' route be listed last?

  1. It is slower
  2. Routes are matched in order, and the wildcard matches everything
  3. Angular sorts routes alphabetically
  4. It is a syntax requirement for TypeScript

What does loadComponent: () => import('./tasks').then(m => m.Tasks) achieve?

  1. Loads the component eagerly at startup
  2. Downloads the Tasks code only when the route is first visited
  3. Imports CSS only
  4. Creates a guard