Routing & Navigation: Building Single Page Apps
7 min read
Routing & Navigation: Building Single Page Apps
Welcome. We are about to modify the fundamental nature of how a user interacts with your application.
In the early days of the web, every click meant a new request to the server, a blank white screen, and a full page reload. It was clunky. Today, we build Single Page Applications (SPAs). In an SPA, we never truly "leave" the page; we simply swap pieces of the view based on the URL.
The Angular Router is the sophisticated engine that manages this illusion. It keeps the URL in the browser address bar in sync with what the user sees on the screen, without ever refreshing the browser.
Let us begin your training. 🧘♂️
1. Setting Up the Angular Router and RouterOutlet
Definition
The Angular Router is a service that presents a specific component based on the current browser URL. The RouterOutlet is a placeholder directive in your template that tells Angular exactly where to drop that component.
The Problem
Without a router, your application is static. You would have to use conditional rendering (@if) to show or hide massive sections of your app manually based on state. This makes deep-linking (sending a specific URL to a friend) impossible because the URL never changes.
The Solution
We define a configuration array—a map—that associates a path (URL segment) with a component. When the URL matches the path, the Router locates the <router-outlet> tag and inserts the component there.
Implementation (Standalone API)
Note: We are using the modern Standalone Component standard (Angular v16+).
Step 1: Define Your Routes
In your application structure, you will typically find app.routes.ts.
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// Empty path redirects to home
{ path: '', redirectTo: '/home', pathMatch: 'full' },
];Step 2: Provide the Router
In modern Angular, we "provide" the router in app.config.ts rather than importing a module.
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes)
]
};Step 3: The Router Outlet
Finally, in your main component (usually app.component.ts), you must import RouterOutlet and place it in the HTML.
// app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet], // 👈 Crucial Step
template: `
<nav>
<!-- Navigation items will go here -->
</nav>
<main>
<!-- The router swaps components right here 👇 -->
<router-outlet></router-outlet>
</main>
`
})
export class AppComponent {}Interesting Fact: The concept of SPAs relies heavily on the HTML5 History API (
pushStateandreplaceState). Before this existed, developers used the "hash" hack (example.com/#/page), known as hash-bang routing, to prevent the browser from reloading. You can still enable hash routing in Angular if you are hosting on a server that doesn't support fallback rewriting!
2. Navigating Between Views: RouterLink and Programmatic Routing
Definition
RouterLink is a directive used in HTML templates to trigger navigation. Programmatic Routing involves using the Router class in your TypeScript code to navigate based on logic (e.g., after a user logs in).
The Problem
If you use a standard HTML anchor tag <a href="/about">About</a>, the browser will treat it as an external request. It will tear down your entire Angular application, reload the CSS/JS, and bootstrap the app again. This is slow and destroys any data currently held in memory.
The Solution
We use routerLink. It intercepts the click event, prevents the default browser refresh, and tells the Angular Router to update the URL and view internally.
Implementation
A. Declarative Navigation (Template)
Use routerLink for static links, like a navigation bar.
// inside a component's template
import { RouterLink, RouterLinkActive } from '@angular/router';
@Component({
imports: [RouterLink, RouterLinkActive],
template: `
<nav>
<!-- Passing a string -->
<a routerLink="/home" routerLinkActive="active-link">Home</a>
<!-- Passing an array (safer for dynamic segments) -->
<a [routerLink]="['/about']" routerLinkActive="active-link">About</a>
</nav>
`,
styles: [`
.active-link { font-weight: bold; color: blue; }
`]
})
export class NavbarComponent {}Note: routerLinkActive applies a CSS class when that route is currently displayed.
B. Imperative Navigation (TypeScript)
Use the Router service when navigation depends on an action completion.
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({ ... })
export class LoginComponent {
// Modern dependency injection
private router = inject(Router);
onLoginSuccess() {
console.log("Login verified. Teleporting user...");
// Navigate to /dashboard
this.router.navigate(['/dashboard']);
}
}Imagination Break: 🛸 Imagine the Router is the pilot of a spaceship.
RouterLinkis a button on the passenger's seat panel.this.router.navigateis the pilot manually punching in coordinates after receiving clearance from the control tower (your logic).
3. Dynamic Routes: Handling Route Parameters
Definition
Dynamic Routes allow you to pass data through the URL. Instead of defining a route for every single item (e.g., /product-1, /product-2), we define a pattern with a variable parameter.
The Problem
You are building an e-commerce site with 10,000 products. You cannot write 10,000 entries in your app.routes.ts. You need a way to say, "This part of the URL is the ID, handle whatever sits there."
The Solution
We use the colon syntax (:) in the route path to define a token. We then extract that token inside the component.
Implementation
Step 1: Configure the Route
// app.routes.ts
export const routes: Routes = [
// :id is a placeholder for any value
{ path: 'profile/:id', component: UserProfileComponent }
];Step 2: Access the Data (The Modern Way)
In older Angular versions, you had to subscribe to ActivatedRoute. In modern Angular (v16+), we can bind route parameters directly to component inputs!
First, enable this feature in app.config.ts:
// app.config.ts
import { withComponentInputBinding } from '@angular/router';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding()) // 👈 Enable this
]
};Now, just use the @Input decorator in your component:
// user-profile.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-user-profile',
standalone: true,
template: `
<h1>User Profile</h1>
<p>Viewing data for user ID: {{ id }}</p>
`
})
export class UserProfileComponent {
// The name 'id' matches the path 'profile/:id'
@Input() id!: string;
ngOnInit() {
// You can use this.id to fetch data from an API immediately
console.log("Fetching data for", this.id);
}
}4. Catch-All Routes: Handling 404 Pages
Definition
A Catch-All Route (or Wildcard Route) acts as a safety net. It matches any URL that does not match the routes defined above it.
The Problem
Users make mistakes. They type /hom instead of /home. Or they follow a broken link. If the Router cannot match the URL to a configuration, the application might crash or show a blank screen, leaving the user confused and alone in the digital void.
The Solution
We use the double asterisk ** path. This is a wildcard that means "anything else."
Implementation
Crucial Rule: The order of routes matters. The Router uses a "First Match Wins" strategy. The Wildcard route must be the last element in your routes array.
// app.routes.ts
import { Routes } from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'profile/:id', component: UserProfileComponent },
// ⚠️ INCORRECT: If you put wildcard here, it will block everything below it.
// ✅ CORRECT: The Wildcard Route (Must be last)
{ path: '**', component: NotFoundComponent }
];Inside NotFoundComponent, you should provide a polite message and a way back to safety:
@Component({
template: `
<div class="error-page">
<h1>404 - Sector Not Found</h1>
<p>The coordinates you entered lead to a black hole.</p>
<a routerLink="/home">Return to Base</a>
</div>
`
})
export class NotFoundComponent {}Industry Standard: Always have a 404 page. It is bad UX to leave a user staring at a broken URL. For enterprise apps, you might even log these 404 occurrences to an analytics service to detect broken links in your marketing emails.
Summary of Best Practices
- Use
routerLinkfor internal links to avoid page reloads. - Order matters in your routes array. Specific routes first, generic/wildcard routes last.
- Use Component Input Binding (
withComponentInputBinding) for cleaner parameter handling. - Lazy Load your routes (not covered here, but keep it in mind) for performance in large apps.
References & Further Reading
Go forth and build your navigation paths. 🛣️
Challenge
You are tasked with setting up the routing for a new e-commerce application. Your goal is to configure the Angular Router to handle navigation between a home page, a product catalog, individual product details, and a 404 page for any invalid URLs.
Requirements:
app.routes.ts: Define an array ofRoutes. This array must include:- A route for the path
'home'that loadsHomeComponent. - A route for the path
'products'that loadsProductCatalogComponent. - A dynamic route for the path
'products/:id'that loadsProductDetailComponent. The:idsegment is a placeholder for the product's unique identifier. - A wildcard route (
'**') that matches any path not previously matched and loadsNotFoundComponent. This must be the last route in the array. - A route that redirects the empty path
''to'/home'.
- A route for the path
app.config.ts: In theApplicationConfig, provide the router usingprovideRouter(). You must also enable the feature that allows route parameters to be bound directly to component inputs.app.component.ts: Update the component's template to include:- A navigation bar with
<a>tags that use therouterLinkdirective to navigate to the 'Home' (/home) and 'Products' (/products) pages. - Apply an 'active-link' CSS class to the currently active navigation link using the
routerLinkActivedirective. - A
<router-outlet>directive to serve as the placeholder where the routed components will be rendered.
- A navigation bar with
product-catalog.component.ts: Implement programmatic navigation. Inject theRouterservice and create a methodviewProduct(productId: string)that navigates to the corresponding product detail page (e.g.,/products/123).product-detail.component.ts: Use modern Angular's component input binding to receive theidfrom the URL. Declare a public propertyiddecorated with@Input()that will automatically be populated with the value from the'products/:id'route.
Expected result
Your final code should correctly implement the routing configuration across the specified files.
app.routes.ts
The routes array should be defined in the correct order, with the specific routes first, followed by the redirect, and ending with the wildcard route.
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { ProductCatalogComponent } from './product-catalog.component';
import { ProductDetailComponent } from './product-detail.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'products', component: ProductCatalogComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];app.config.ts
The providers array should contain a call to provideRouter with the routes array and the withComponentInputBinding() feature enabled.
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding())
]
};app.component.ts
The template should include navigation links using routerLink and routerLinkActive, as well as the essential <router-outlet>.
// imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a routerLink="/home" routerLinkActive="active-link">Home</a>
<a routerLink="/products" routerLinkActive="active-link">Products</a>
</nav>
<router-outlet></router-outlet>
`product-catalog.component.ts
This component should inject the Router service and use the navigate method to change routes programmatically.
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({ /* ... */ })
export class ProductCatalogComponent {
private router = inject(Router);
viewProduct(productId: string) {
this.router.navigate(['/products', productId]);
}
}product-detail.component.ts
This component must have an @Input() property that matches the name of the dynamic route parameter (id).
import { Component, Input } from '@angular/core';
@Component({ /* ... */ })
export class ProductDetailComponent {
@Input() id!: string;
}