Sub topic 1
How Client-Side Routing Works in Angular
A single-page application (SPA) loads one HTML document and then swaps views in the browser, but users still expect URLs to work as they do on traditional sites. Bookmarks should open the right screen, the Back button should go back, and a link shared in chat should land on the same product page. The Angular Router provides this. This chapter explains how it works before later chapters cover each feature.
Prerequisites
This chapter assumes you already know:
- TypeScript fundamentals, including modules, arrow functions, and type annotations.
- Angular components and templates.
- Standalone components and the
inject()function. - Dependency injection and services in Angular.
- Basic RxJS Observables, since the Router reports much of its state through streams.
You should also be able to create and run a project with the Angular CLI (ng new, ng serve).
Server-Side Routing vs Client-Side Routing
In a traditional multi-page site, the server does the routing. Each URL change sends a request, the server picks a template, and the browser throws away the current page and renders a new one. In an SPA, the server sends index.html and the JavaScript bundles once. From then on, the browser changes the URL itself and the application decides what to show.
| Aspect | Server-side routing | Client-side routing (Angular Router) |
|---|---|---|
| Who maps URL to view | The server | JavaScript running in the browser |
| Cost of a navigation | Full HTTP request and page reload | Component swap, often with no request at all |
| Application state | Lost on every navigation | Kept in memory (services, caches) |
| Back/Forward buttons | Handled natively by the browser | Handled through the History API |
| Deep link on first load | Works by default | Needs the server to return `index.html` for app URLs |
| SEO and first paint | HTML arrives ready to show | Needs server-side rendering or prerendering for the same result |
The last two rows are where most production problems with SPAs come from. They are covered below.
The Browser Mechanism Underneath
Client-side routing depends on the browser History API. Three parts of it matter here:
history.pushState(state, '', url)changes the address bar and adds a history entry without loading a page.history.replaceState(...)does the same but overwrites the current entry.- The
popstateevent fires when the user presses Back or Forward. The URL has already changed, and the app must render the matching view.
Here is a client-side router in plain TypeScript, with no Angular. Compile it, include it in a page that has <div id="app"></div> and a few <a href="/about"> links, and serve it from a server that returns that page for every path.
// mini-router.ts
const views: Record<string, string> = {
'/': 'Home page',
'/about': 'About page',
'/products': 'Product list',
};
function render(path: string): void {
const outlet = document.getElementById('app')!;
outlet.textContent = views[path] ?? 'Not found';
}
// Intercept same-origin link clicks so the browser does not reload the page.
document.addEventListener('click', (event: MouseEvent) => {
const link = (event.target as HTMLElement).closest('a');
if (!link || link.origin !== location.origin) return;
if (event.ctrlKey || event.metaKey || event.shiftKey || event.button !== 0) return;
event.preventDefault();
history.pushState({}, '', link.pathname);
render(link.pathname);
});
// Back/Forward buttons: the URL has already changed, so re-render.
window.addEventListener('popstate', () => render(location.pathname));
// Initial load (deep link): render whatever URL the user arrived on.
render(location.pathname);The Angular Router does the same three things: it intercepts navigation, updates history, and renders on first load and on popstate. On top of that it adds route matching, parameters, nested views, guards, data loading, lazy code loading, and a typed API.
What the Angular Router Does on Each Navigation
The Router treats every navigation as a pipeline. A navigation can start from a link click, a call in code, a popstate event, or the initial page load. Knowing the stages makes later topics easier to place: guards and resolvers are steps in this pipeline.
The UrlTree
The Router does not match routes against raw strings. It first parses the URL into a UrlTree, a structured object holding path segments, matrix parameters, query parameters, and a fragment. You can run the parser yourself:
// url-tree-demo.ts (run inside any Angular project, e.g. with npx tsx)
import { DefaultUrlSerializer, PRIMARY_OUTLET } from '@angular/router';
const serializer = new DefaultUrlSerializer();
const tree = serializer.parse('/products/42;color=red?sort=price&page=2#reviews');
const segments = tree.root.children[PRIMARY_OUTLET].segments;
console.log(segments.map(s => s.path)); // [ 'products', '42' ]
console.log(segments[1].parameters); // { color: 'red' }
console.log(tree.queryParams); // { sort: 'price', page: '2' }
console.log(tree.fragment); // 'reviews'
console.log(serializer.serialize(tree)); // '/products/42;color=red?sort=price&page=2#reviews'Two details matter. All parameter values are strings, so '2' is not 2. Also, guards can return a UrlTree to redirect, which is why the guard example later in this tutorial calls router.createUrlTree(...).
Recognition and the Router State
During recognition, the Router walks your Routes array and builds a router state. This is a tree of activated routes, one per matched route, each holding its parameters, data, and component. Components later read their slice of that tree through ActivatedRoute or through component inputs. Matching is ordered: the first route that matches wins. That ordering explains why a wildcard route must come last, a point the chapter on redirects covers.
A Minimal Angular Router Setup
This is the smallest complete app that shows the pieces working together. Later chapters explain each one; here, look at where each part of the pipeline happens.
// main.ts
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Routes, RouterLink, RouterOutlet } from '@angular/router';
@Component({ selector: 'app-home', standalone: true, template: `<h2>Home</h2>` })
class HomeComponent {}
@Component({ selector: 'app-about', standalone: true, template: `<h2>About</h2>` })
class AboutComponent {}
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
template: `
<nav>
<a routerLink="/">Home</a> |
<a routerLink="/about">About</a>
</nav>
<router-outlet />
`,
})
class AppComponent {}
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
}).catch(err => console.error(err));provideRouter(routes)registers the Router and triggers the initial navigation.routerLinkintercepts clicks and asks the Router to navigate. It plays the role of the click handler in the plain TypeScript example.<router-outlet />is where activated components are rendered. It plays the role of#app.
The CLI-generated index.html also contains <base href="/">. The Router resolves relative URLs against it. If the app is deployed under a sub-path such as /shop/, the base href must match (ng build --base-href /shop/), or links and asset paths will break.
Common Errors
Full page reloads from plain href links
Using <a href="/about"> in an Angular template works, but it reloads the whole app. In-memory state is lost and bundles are fetched again. Use routerLink for in-app links, and keep href for external sites.
404 when refreshing a deep link in production
ng serve sends index.html back for any unknown path, so deep links work during development. A plain static host does not. It looks for a file named products/42, finds nothing, and returns 404. Configure a fallback. For nginx:
location / {
try_files $uri $uri/ /index.html;
}Hash-based URLs (/#/products/42) avoid this problem because the server never sees the part after #. The trade-offs are covered in the chapter on location strategies.
Expecting typed parameters
Route and query parameters arrive as strings. Convert them yourself (Number(id)) and validate them, because users can type any URL.
Assuming navigation is instant
Navigations are asynchronous. Guards and resolvers can delay them, cancel them, or redirect them. Code that reads router.url right after starting a navigation can see the old URL.
Exercise
A user on your deployed app at https://example.com/orders/17 presses F5 and gets the web server's 404 page, yet clicking through to the same page from the home screen works. Explain why, using the navigation flow from this chapter, and name two ways to fix it.
Show answer
Clicking a routerLink is handled entirely in the browser. The Router calls pushState and renders the component, so no request reaches the server. Pressing F5 makes the browser send GET /orders/17 to the server, which has no file at that path and returns 404 before Angular ever loads. Fix 1: configure the server to fall back to index.html for unknown paths (for example nginx try_files $uri $uri/ /index.html). Fix 2: switch to the hash location strategy, so the URL becomes /#/orders/17 and the server only ever receives a request for /.
Exercise
Parse '/search;mode=grid?q=shoes&page=3#top' with DefaultUrlSerializer. What are the primary outlet's segment paths, the matrix parameters of the last segment, the queryParams, the fragment, and the type of queryParams['page']?
Show answer
Segment paths: ['search']. Matrix parameters of 'search': { mode: 'grid' }. queryParams: { q: 'shoes', page: '3' }. Fragment: 'top'. queryParams['page'] is the string '3', not a number, because every URL parameter is parsed as a string.
Exercise
In the plain TypeScript mini-router, which line corresponds to Angular's RouterLink, which to RouterOutlet, and what would break if you removed the popstate listener?
Show answer
The document click handler that calls preventDefault and history.pushState corresponds to RouterLink. The #app element updated by render() corresponds to RouterOutlet. Without the popstate listener, Back and Forward would still change the address bar, but the page content would stay on the old view, so the URL and the screen would disagree.