Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 74 ยท Routing

Routing Basics

Set up the Angular router with provideRouter, define Routes, render pages in router-outlet, link with routerLink, and handle redirects and wildcard routes.

An Angular application is a single HTML page. When the user clicks "About", the browser should not load a new document; Angular should swap one component for another and update the address bar so the page can still be bookmarked, shared and reloaded. The piece that does this is the router: it maps URLs to components, renders the matching component, and keeps the URL and the screen in sync.

This lesson covers the core vocabulary you need before anything else in routing: the Routes array, provideRouter, <router-outlet>, routerLink, active-link styling, redirects and the wildcard route. The next lessons add parameters, child and lazy routes and guards.

Angular's router needs the Angular compiler and a real browser app, so the real Angular code in this lesson is read-only. The runnable examples are hand-written stand-ins: a tiny route matcher and a link-activity checker written in plain TypeScript, so you can experiment with the ideas (first match wins, pathMatch, wildcards) on the site's runner. They are not the real router.

The big picture

Three things cooperate. A route table lists which URL path shows which component. The router takes the current URL, walks the table from top to bottom and picks the first route that matches. A <router-outlet> is a placeholder in a template where the chosen component is rendered.

flowchart LR
  U["URL: /about"] --> R["Router"]
  T["Routes array<br/>first match wins"] --> R
  R --> C["AboutComponent"]
  C --> O["Rendered inside<br/>router-outlet"]

The router matches the URL against the route table and renders the winning component into the outlet.

Defining routes

A route is an object, and the route table is an array of them. By convention it lives in app.routes.ts:

TypeScript
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';

export const routes: Routes = [
  { path: '', component: HomeComponent, title: 'Home' },
  { path: 'about', component: AboutComponent, title: 'About us' },
  { path: 'company', redirectTo: 'about', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent, title: 'Page not found' },
];

Some rules to remember:

  • Paths have no leading slash. You write 'about', not '/about'. The empty string '' is the root URL.
  • Order matters. The router tests routes from the top and uses the first match, so specific routes go first and the catch-all goes last.
  • component says what to render. The component must be standalone (the default in modern Angular) or imported where it's used.
  • title sets the browser tab title when the route is active. The next lesson shows how to compute titles dynamically.

Registering the router

The route table does nothing until you give it to Angular. In a standalone app that happens in the application config, with provideRouter:

TypeScript
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

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

provideRouter takes the routes and, optionally, feature functions whose names start with with. They switch on extra behavior. withComponentInputBinding() lets the router pass route data straight into component input()s (covered in the next lesson). Others you will meet include withPreloading (lazy-loading strategy) and withRouterConfig. This is the same bootstrapApplication(AppComponent, appConfig) setup you saw in Setup and the Angular CLI; older NgModule apps used RouterModule.forRoot(routes) for the same job.

Showing pages with router-outlet

The root component needs somewhere to render the active page. Place <router-outlet /> there, and import the RouterOutlet directive so the template knows it:

TypeScript
// app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink, RouterLinkActive],
  template: `
    <header>
      <nav>
        <a routerLink="/" routerLinkActive="active"
           [routerLinkActiveOptions]="{ exact: true }">Home</a>
        <a routerLink="/about" routerLinkActive="active">About</a>
      </nav>
    </header>

    <main>
      <router-outlet />
    </main>
  `,
})
export class AppComponent {}

The header and nav stay on screen for ever. Only what is inside <main> changes as the URL changes. A component placed in the outlet is created when its route becomes active and destroyed when the user leaves, which is why lifecycle hooks matter for pages too.

A plain <a href="/about"> would make the browser request a new document and restart the whole app. routerLink instead tells the router to navigate in place:

HTML
<!-- static path -->
<a routerLink="/about">About</a>

<!-- an array of segments, handy with variables -->
<a [routerLink]="['/courses', course.id]">{{ course.title }}</a>

<!-- relative to the current route -->
<a routerLink="details">Details</a>

Leading / means "from the root"; without it the path is relative to the current route. On an <a> element, Angular also writes a real href, so right-click "Open in new tab", crawlers and screen readers all work. Use routerLink for anything the user clicks to move around, and reserve Router.navigate() for navigation that happens in code (after saving a form, for example).

routerLinkActive adds one or more CSS classes to an element while its link matches the current URL. By default the match is inclusive: a link to /courses stays active on /courses/angular, which is usually what a menu wants. The exception is the home link: / is a prefix of every URL, so it would always be active. Add [routerLinkActiveOptions]="{ exact: true }" there.

This stand-in models the two modes by comparing URL segments:

TypeScript Stand-in: which links are active?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Square brackets mark the active links, and the last line shows the classic mistake: without exact, Home would light up on every page. Real routerLinkActive also ignores query parameters by default, which is why /about?tab=team still activates About.

Redirects and the empty path

A redirect route has redirectTo instead of component. It's how you move an old URL to a new one, or send the root URL to a default page:

TypeScript
export const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'company', redirectTo: 'about', pathMatch: 'full' },
  { path: 'about', component: AboutComponent },
];

pathMatch decides how much of the URL a route's path must cover:

  • 'prefix' (the default) matches when the URL starts with the path.
  • 'full' matches only when the whole remaining URL equals the path.

The empty path '' is a prefix of every URL. A redirect from '' without pathMatch: 'full' would therefore capture everything, so the router makes you state pathMatch explicitly on redirects, and 'full' is almost always what you mean for ''.

The wildcard route

The path '**' matches any URL. Put it last, as the "not found" page. If no route matches and you have no wildcard, the router reports an error instead of rendering anything. A wildcard is also the place to redirect unknown URLs to a sensible default if you don't want a 404 page.

Here is a miniature router that follows these rules (first match wins, pathMatch, wildcard, redirects followed to their destination):

TypeScript Stand-in: a mini router with first-match-wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The "broken" table shows why pathMatch matters: the prefix redirect from '' matches /home too and sends it back to home over and over. Real Angular guards against this by requiring you to say pathMatch and by validating the config.

Passing route data into components

With withComponentInputBinding() enabled, a routed component can declare input()s whose names match route parameters, query parameters or data entries, and the router fills them in. You will use this heavily in the next lesson; for now just remember that the routed component is an ordinary component, and its inputs are just another way data arrives.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the router do when several routes could match the URL?

    Routes are tested in array order and the first match wins, which is why specific routes go before the '**' wildcard.
  2. 2. Why is pathMatch "full" usually needed on a redirect from the empty path?

    An empty path is a prefix of every URL. With the default 'prefix' mode the redirect would capture all navigation, so you ask for a match against the whole URL.
  3. 3. What is the difference between <a href="/about"> and <a routerLink="/about"> in an Angular app?

    A normal href triggers a full page load. routerLink asks the router to swap the component in place and update the URL, so state in services and the shell is kept.
  4. 4. Why does the Home link usually need [routerLinkActiveOptions]="{ exact: true }"?

    Inclusive matching treats "/" as the start of every URL. Exact matching restricts the highlight to the home page itself.

Summary

  • The router maps URLs to components; Routes is an array of route objects, and the first match wins.
  • Register routes with provideRouter(routes, ...features) in app.config.ts; features like withComponentInputBinding() add behavior.
  • Render the active component with <router-outlet />; paths in the table have no leading slash.
  • Use routerLink instead of href to navigate without a page reload, and routerLinkActive (with exact: true for the home link) to style the current link.
  • Redirects use redirectTo and need pathMatch; use 'full' for the empty path.
  • Put the '**' wildcard last for a "not found" page.
  • In this lesson the Angular code is read-only; the runnable examples are small stand-ins of the matching logic.

Next: Route Parameters, Query Params and Navigation