Route Parameters & Guards
Real apps have URLs like /products/42 or /search?q=lamp&page=2, and some pages should only be reachable by signed-in users. This lesson covers route parameters, query parameters and guards.
Route parameters
A path segment starting with : is a parameter:
export const routes: Routes = [
{ path: 'products', component: ProductList },
{ path: 'products/:id', component: ProductDetail },
];The easiest way to read it is to let the router bind parameters to component inputs. Enable it once in app.config.ts:
provideRouter(routes, withComponentInputBinding())Now an input with the same name as the parameter receives its value:
import { Component, computed, input, numberAttribute } from '@angular/core';
import { RouterLink } from '@angular/router';
const PRODUCTS = [
{ id: 41, name: 'Standing desk', price: 420 },
{ id: 42, name: 'Ergonomic chair', price: 310 },
];
@Component({
selector: 'app-product-detail',
imports: [RouterLink],
template: `
@if (product(); as p) {
<h2>{{ p.name }}</h2>
<p>Price: {{ p.price }} USD</p>
<a [routerLink]="['/products', p.id + 1]">Next product →</a>
} @else {
<p>Product {{ id() }} not found.</p>
}
`,
})
export class ProductDetail {
id = input.required({ transform: numberAttribute }); // from /products/:id
product = computed(() => PRODUCTS.find((p) => p.id === this.id()));
}Because id is a signal, navigating from /products/42 to /products/43 reuses the same component and simply updates the input — product recomputes automatically.
Note: Without input binding, inject
ActivatedRouteand readroute.snapshot.paramMap.get('id')or subscribe toroute.paramMap.
Query parameters
Query parameters (?q=lamp&page=2) are optional and unordered — ideal for search, filters and pagination. With withComponentInputBinding() they bind to inputs too. To set them:
<a routerLink="/search" [queryParams]="{ q: 'lamp', page: 2 }">Lamps, page 2</a>Parsing a query string is a nice warm-up in plain TypeScript (the router does this for you):
function parseQuery(url: string): Record<string, string> {
const query = url.split('?')[1] ?? '';
const result: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(query)) {
result[key] = value;
}
return result;
}
console.log(parseQuery('/search?q=desk%20lamp&page=2'));
console.log(parseQuery('/search'));{ q: 'desk lamp', page: '2' }
{}
Values always arrive as strings — convert with numberAttribute / booleanAttribute transforms or Number(...).
Route guards
A guard is a function the router calls before activating (or leaving) a route. It returns:
| Return value | Effect |
|---|---|
true |
Navigation continues |
false |
Navigation is cancelled |
A UrlTree |
Navigation is redirected (e.g. to /login) |
A Promise / Observable of the above |
Router waits for the answer |
// auth.guard.ts
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { Auth } from './auth';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(Auth);
if (auth.isLoggedIn()) return true;
return inject(Router).createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
// app.routes.ts
{ path: 'account', component: Account, canActivate: [authGuard] }The guard's decision logic is plain TypeScript. Here it is with a fake session and a string standing in for the UrlTree:
type GuardResult = true | false | { redirect: string };
interface Session { user: string | null; roles: string[]; }
function makeGuard(session: Session, requiredRole?: string) {
return (url: string): GuardResult => {
if (!session.user) return { redirect: `/login?returnUrl=${encodeURIComponent(url)}` };
if (requiredRole && !session.roles.includes(requiredRole)) return false;
return true;
};
}
const guest: Session = { user: null, roles: [] };
const editor: Session = { user: 'mai', roles: ['editor'] };
console.log(makeGuard(guest)('/account'));
console.log(makeGuard(editor)('/account'));
console.log(makeGuard(editor, 'admin')('/admin/users'));{ redirect: '/login?returnUrl=%2Faccount' }
true
false
Kinds of guards
| Guard | Asked when… |
|---|---|
canActivate |
Entering a route |
canActivateChild |
Entering any child of a route |
canDeactivate |
Leaving a route (e.g. "discard unsaved changes?") |
canMatch |
Deciding whether a route config should match at all (also prevents lazy loading) |
resolve |
Not a guard but similar: loads data before the route activates |
Tip: Guards improve the user experience, but they are not security. Anyone can read your JavaScript. Always enforce permissions on the server too.
Test yourself
With withComponentInputBinding(), how does ProductDetail receive the :id from products/:id?
- Through an input named
id - Through a service called Params
- Through localStorage
- It cannot; you must use ActivatedRoute
What should a CanActivateFn return to send unauthenticated users to /login?
'/login'as a stringrouter.createUrlTree(['/login'])nullwindow.open('/login')
What type do query parameter values have when they arrive?
- number
- string
- boolean
- Whatever type you put in the link