Angular Router

Angular Router in Angular: Picture a large metro network. A rider arrives knowing only a destination name, and the station's wayfinding map turns that name…

The Analogy: A Subway Wayfinding System

Picture a large metro network. A rider arrives knowing only a destination name, and the station's wayfinding map turns that name into a specific platform: each entry on the map pairs a route (a named destination) with the exact platform that serves it. Angular's Router is that map. You hand it a URL - the destination a user typed or clicked - and it consults an ordered table of path-to-component pairs to decide which view belongs on screen. Nothing about the building changes; only the sign you followed decides where you end up.

Some platforms serve many different trains, told apart by a "toward ___" board that fills in the final destination. That fill-in slot is a route parameter, the :id in users/:id - one platform, one component, parameterized by a value that varies per visit. And notice the single information screen mounted above the platform: it is a fixed frame whose contents swap as each train arrives. That screen is the router-outlet - one location in your layout where the Router paints whichever component the current URL selected.

Bigger interchanges nest a local map inside the station map: once you are inside the "museum quarter" complex you follow a smaller board to specific exits. Those are child routes, defined under a parent path so the parent's outlet hosts them. A turnstile that only opens for a valid ticket is a canActivate guard, checking a condition before it lets you reach the platform at all. And an express line whose cars are only rolled out when demand appears is a lazily loaded feature module - its code is fetched the first time someone actually travels there, not when the station opens.

The failure mode is a wayfinding table that is inconsistent or incomplete. If two entries claim the same destination, the map resolves ties by order - the first match wins - so a carelessly ordered table can send every rider to the wrong platform. Put a "catch-all" entry at the top and it swallows every destination before the specific ones are ever consulted. Worse, omit the "all other trains" fallback entirely and an unknown destination strands the rider at a blank platform: in Angular, a routing table with no wildcard ** route renders nothing for a URL it does not recognize, instead of showing a proper "not found" page.


Syntax or Core Structure

Routing starts with a Routes array - the wayfinding table. Each entry maps a path to the component that should fill the outlet, with parameter slots written as :name and a final wildcard ** catching everything unmatched. You register it once with RouterModule.forRoot(routes), drop a single <router-outlet> where views should appear, and navigate with routerLink in templates or Router.navigate in code.

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'users/:id', component: UserComponent },
  { path: '**', component: NotFoundComponent }
];

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

The template provides the outlet and the links. routerLink builds URLs without a full page reload, and routerLinkActive styles the link for the current route:

<nav>
  <a routerLink="/" routerLinkActive="active">Home</a>
  <a routerLink="/users/42">User 42</a>
</nav>
<router-outlet></router-outlet>

At its core the Router is a pure function: given a URL, walk the table in order and return the first entry that matches, extracting any :param segments along the way. Modeling that matcher in plain JavaScript makes the behavior - including the wildcard fallback and parameter capture - fully verifiable:

const routes = [
  { path: '', component: 'HomeComponent' },
  { path: 'about', component: 'AboutComponent' },
  { path: 'users/:id', component: 'UserComponent' },
  { path: '**', component: 'NotFoundComponent' }
];

function match(url) {
  const seg = url.split('/').filter(s => s !== '');
  for (const r of routes) {
    if (r.path === '**') return { component: r.component, params: {} };
    const pat = r.path === '' ? [] : r.path.split('/');
    if (pat.length !== seg.length) continue;
    const params = {};
    let ok = true;
    for (let i = 0; i < pat.length; i++) {
      if (pat[i].startsWith(':')) params[pat[i].slice(1)] = seg[i];
      else if (pat[i] !== seg[i]) { ok = false; break; }
    }
    if (ok) return { component: r.component, params };
  }
}

console.log(JSON.stringify(match('')));
console.log(JSON.stringify(match('about')));
console.log(JSON.stringify(match('users/42')));
console.log(JSON.stringify(match('nope/xyz')));

Output:

{"component":"HomeComponent","params":{}}
{"component":"AboutComponent","params":{}}
{"component":"UserComponent","params":{"id":"42"}}
{"component":"NotFoundComponent","params":{}}

The empty path resolves to Home, users/42 captures id: "42", and the unknown nope/xyz falls through to the wildcard - exactly the real Router's behavior.


Technical Depth: Parameters, Guards, and Match Order

Reading route parameters

A component reached through users/:id needs the actual id. Angular injects ActivatedRoute, which exposes parameters two ways: a one-time snapshot and a live paramMap Observable. The snapshot is read once when the component is created; the Observable emits every time the parameter changes, even while the component instance is reused.

@Component({ selector: 'app-user', template: '<h2>User {{ id }}</h2>' })
export class UserComponent implements OnInit {
  id = '';
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    this.route.paramMap.subscribe(pm => this.id = pm.get('id') ?? '');
  }
}

The full route table supports far more than path and component. These are the entries you reach for most:

PropertyPurpose
pathURL segment to match; :name marks a parameter
componentComponent rendered into the outlet on a match
redirectToSend this path to another, with pathMatch
childrenNested routes rendered in the parent's outlet
canActivateGuards that must pass before the route loads
loadChildrenLazily load a feature module on first visit
**Wildcard catch-all for unmatched URLs

Route guards

A guard is the turnstile: a function that returns true to allow navigation or a UrlTree to redirect. canActivate runs before the route activates, so a protected page never even constructs its component for an unauthorized user. Modeled as a predicate, the gate is easy to verify:

const session = { loggedIn: false };
function canActivate() { return session.loggedIn; }

function navigate(url) {
  if (url === 'admin' && !canActivate()) return 'redirected to /login';
  return 'activated /' + url;
}

console.log(navigate('admin'));   // blocked
session.loggedIn = true;
console.log(navigate('admin'));   // now allowed

Output:

redirected to /login
activated /admin

While logged out, the guard diverts the rider to the login page; once the session flips to authenticated, the same navigation reaches the admin platform. Modern Angular writes guards as plain functions with inject(), registered as canActivate: [authGuard].

Match order and the wildcard

The Router matches top to bottom and stops at the first hit, so order is not cosmetic - it is the algorithm. The wildcard ** matches everything, which is exactly why it must sit last. Placed first, it swallows every URL before any specific route is consulted:

function firstMatch(order, url) {
  for (const p of order) {
    if (p === '**') return 'NotFound';
    if (p === url) return url + ' page';
  }
  return 'no match';
}

const good = ['', 'about', '**'];   // wildcard last
const bad  = ['**', '', 'about'];   // wildcard first

console.log('good order -> ' + firstMatch(good, 'about'));
console.log('bad order  -> ' + firstMatch(bad, 'about'));

Output:

good order -> about page
bad order  -> NotFound

Same routes, same URL, opposite result. The lesson generalizes: list the most specific paths first, redirects and static paths before parameterized ones, and the wildcard dead last.


Real World Example: A Product Detail Page

A catalog is the routing feature every app grows: a list at /products, a detail page at /products/:id, and a guard so only signed-in staff reach /admin. The detail component reads the :id from the route and loads that product. Here is a version that reads the id from the snapshot - the most common first attempt:

@Component({
  selector: 'app-product-detail',
  template: '<h2>Product #{{ id }}</h2>'
})
export class ProductDetailComponent implements OnInit {
  id = '';
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    // read once, when the component is first created
    this.id = this.route.snapshot.paramMap.get('id') ?? '';
  }
}

The catch is that the Router reuses a component instance when navigating between two URLs served by the same route - going from /products/1 to /products/2 does not destroy and recreate ProductDetailComponent, so ngOnInit never fires again. The snapshot, read once, goes stale. Compare a snapshot read against a stream that re-reads on every navigation:

const navigations = ['product/1', 'product/2', 'product/3'];
const paramOf = u => u.split('/')[1];

// snapshot: captured on first activation, never re-read
let snapshotId = paramOf(navigations[0]);
const snapshotViews = navigations.map(() => snapshotId);

// paramMap stream: re-reads on every navigation
const streamViews = navigations.map(paramOf);

console.log('snapshot shows: ' + snapshotViews.join(', '));
console.log('paramMap shows: ' + streamViews.join(', '));

Output:

snapshot shows: 1, 1, 1
paramMap shows: 1, 2, 3

The two rows tell the whole story. Both start correctly at product 1, because on first activation the component is freshly created and the snapshot is accurate. The divergence begins the moment the user navigates within the same route: the snapshot version is frozen at 1 forever, while the stream version tracks 2 and 3 as the URL changes.

In a real catalog this manifests as a page that shows the right title the first time you open it, then displays product 1's name, price, and photos no matter which product you click next. Because there is no error - no console warning, no exception - it is a maddening bug to diagnose. The URL in the address bar reads /products/3 while the content stubbornly describes product 1.

The guard side of the feature behaves well: canActivate runs on every activation regardless of reuse, so the admin turnstile keeps working. It is specifically the per-parameter data load that the snapshot approach gets wrong, and only when the same route is reused. That narrow reproduction window is why the bug so often ships to production - a quick click-through during development, opening each product from the list fresh, never triggers it.

The genuine design flaw is reading route.snapshot.paramMap in ngOnInit for a route the Router will reuse. The snapshot is a single point-in-time reading, but the component's lifetime spans multiple parameter values. The fix is to treat the parameter as what it is - a stream - and subscribe to route.paramMap, reloading the product on each emission (ideally with switchMap into the data service, and takeUntil to tear down). The snapshot is fine only when you are certain the route is never reused, which is a fragile assumption to bake into a detail page.


Common Mistakes

  1. Reading snapshot.paramMap for a reused route. When the Router reuses a component across parameter changes, the snapshot is stale. Subscribe to route.paramMap (or route.params) so parameter updates flow through.
  1. Putting the wildcard route first. ** matches everything, so any route listed after it is unreachable. It must be the last entry in the table.
  1. Forgetting the wildcard entirely. With no ** route, an unknown URL renders an empty outlet instead of a proper "not found" page. Always add a catch-all.
  1. Omitting pathMatch: 'full' on an empty-path redirect. { path: '', redirectTo: '/home' } without pathMatch: 'full' uses prefix matching and can redirect every URL. Empty-path redirects need 'full'.
  1. Using href instead of routerLink. A plain href triggers a full page reload, discarding application state. Use routerLink for in-app navigation.
  1. Leading slashes on child route paths. Child path values are relative to the parent; a leading / makes them absolute and breaks nesting. Write path: 'edit', not path: '/edit'.
  1. Forgetting <router-outlet>. Without an outlet, matched components have nowhere to render and the page stays blank even though the URL changed.
  1. Doing async work directly in a guard without returning it. A guard must return the boolean/UrlTree (or an Observable/Promise of one); firing an async check and returning nothing lets navigation proceed unguarded.
  1. Not lazy-loading large feature areas. Eagerly importing every feature bloats the initial bundle. Use loadChildren/loadComponent so rarely visited sections load on demand.

Best Practices

  • Read route parameters from the paramMap Observable, not the snapshot, unless you are certain the route is never reused. It is the safe default for any :id detail page.
  • Order the route table from most specific to least, with redirects and static paths first, parameterized paths next, and the wildcard ** always last.
  • Always include a wildcard route pointing at a dedicated not-found component so unknown URLs fail gracefully.
  • Lazy-load feature areas with loadChildren or loadComponent. It keeps the initial bundle small and speeds up first paint.
  • Write guards as small, injectable functions that return a boolean or a UrlTree, and prefer redirecting (returning a UrlTree) over silently blocking.
  • Keep a dedicated routing module (or a single routes constant) per feature so the URL structure is documented in one readable place.
  • Use routerLinkActive to reflect the current route in navigation UI instead of manually comparing URLs.
  • Combine parameter streams with switchMap when a parameter change should trigger a fresh data load, cancelling the previous request automatically.

Practice Exercises

  1. Build a three-route app. Configure Routes for a home page, an about page, and a users/:id detail page, add a <router-outlet> and routerLink navigation, and confirm each URL renders the matching component.
  1. Fix the stale-parameter bug. Start from a detail component that reads route.snapshot.paramMap, navigate between two ids served by the same route to observe the stale value, then convert it to subscribe to route.paramMap and verify the view updates.
  1. Add a route guard. Write a canActivate guard backed by a simple auth service that returns a UrlTree redirect to /login when logged out, protect an admin route with it, and test both the blocked and allowed paths.
  1. Introduce lazy loading and a wildcard. Move a feature area behind loadChildren so it loads on first visit, add a ** route to a not-found component, and confirm an unknown URL lands on the not-found page while the lazy route still resolves.