← Learning Hub
Advanced

Route Parameters, Guards and Lazy Loading

Reading route parameters

Turn on withComponentInputBinding() and route parameters arrive as component inputs - the simplest way to read them.

Real apps need more than simple routes: product pages need an id from the address, admin pages should only open for admins, and big apps should load each section's code only when it's needed. Route parameters, guards and lazy loading cover these needs and are standard in every production Angular app.

Example
// app.config.ts
import { provideRouter, withComponentInputBinding } from '@angular/router';
export const appConfig = { providers: [provideRouter(routes, withComponentInputBinding())] };

// app.routes.ts
export const routes: Routes = [
  { path: 'products/:id', component: ProductPage },
];

// product-page.ts
@Component({ selector: 'app-product-page', template: `<h1>Product {{ id() }}</h1>` })
export class ProductPage {
  id = input.required<string>();      // filled from :id
}

Lazy loading

Load a part of the app only when the user opens it. The first page then downloads less code and opens faster.

Example
export const routes: Routes = [
  { path: '', component: Home },
  { path: 'admin', loadComponent: () => import('./admin/admin').then(m => m.Admin) },
  { path: 'shop', loadChildren: () => import('./shop/shop.routes').then(m => m.SHOP_ROUTES) },
  { path: '**', component: NotFound },
];

Guards: who may open a page

A guard is a function that runs before a route opens. Return true to allow it, or a UrlTree to send the user somewhere else.

Example
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const loggedIn: CanActivateFn = () => {
  const auth = inject(AuthService);
  return auth.isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);
};

// { path: 'orders', component: Orders, canActivate: [loggedIn] }

Navigating from code

Example
private router = inject(Router);
afterSave() { this.router.navigate(['/products', 42]); }
Guards only protect the screens. Real protection of data always happens on the server - a clever user can change any code running in their browser.
Key points
  • withComponentInputBinding() turns route params into inputs.
  • loadComponent / loadChildren lazy-load parts of the app.
  • Guards decide who may open a route - but the server must still check.

📝 Test yourself

1. What does loadComponent do?
2. What should a guard return to send the user to /login?
3. Fill in the path that catches every unknown address:
{ path: '', component: NotFound }