Angular Tutorial 0/42 lessons ~6 min read Lesson 15

    Angular Router

    Learn Angular Router, including SPA routing, route configuration, router-outlet, routerLink, programmatic navigation, route parameters, query parameters, child routes, redirects, wildcard routes, guards, lazy loading, resolvers, and enterprise routing architecture.

    Course progress0%
    Focus
    45 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    By the end of this lesson, you will understand:

    • What routing means in Angular and why it is essential for Single Page Applications.
    • How Angular Router, route configuration, router-outlet, and routerLink work.
    • How to use programmatic navigation, route parameters, query parameters, redirects, wildcard routes, and child routes.
    • How route guards, lazy loading, route data, and resolvers fit into enterprise routing architecture.
    • Why frontend guards are not a backend security boundary.

    Introduction

    Imagine you're building an e-commerce application with pages such as Home, Products, Product Details, Cart, Checkout, Orders, and Profile.

    Users expect meaningful URLs:

    text
    /
    /products
    /products/101
    /cart
    /checkout
    /orders
    /profile

    Traditional websites may request a new HTML document from the server for every navigation. Angular applications commonly follow the Single Page Application model: the application shell loads once, and Angular dynamically changes the displayed view based on the URL.

    This is the responsibility of the Angular Router.

    A Real-World Story

    Imagine you're building an enterprise banking application with routes such as:

    text
    /dashboard
    /accounts
    /accounts/12345
    /transactions
    /beneficiaries
    /payments
    /profile
    /admin
    text
    Browser URL
    Angular Router
    Route Configuration
    Matching Component
    router-outlet
    Page Displayed

    The Router becomes an important part of the application's overall architecture because URLs, views, authentication checks, lazy features, and navigation state all meet there.

    What Is Angular Router?

    Angular Router is Angular's official navigation library for managing application views based on browser URLs.

    It supports route configuration, URL-based navigation, route parameters, query parameters, nested routes, redirects, lazy loading, route guards, navigation events, route data, and route resolvers.

    text
    URL
    Router
    Route Match
    Component
    Rendered View

    Single Page Application Routing

    In a traditional multi-page website, navigation often triggers a browser request, server response, new HTML page, and full page reload.

    In an Angular SPA, Angular Router updates the URL, matches a route, and renders the matching component without reloading the whole application during normal client-side navigation.

    Basic Route Configuration

    typescript
    import { Routes } from '@angular/router';
    import { HomeComponent } from './home/home.component';
    import { ProductsComponent } from './products/products.component';
    import { CartComponent } from './cart/cart.component';
    export const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'products', component: ProductsComponent },
    { path: 'cart', component: CartComponent }
    ];

    Now Angular understands that /, /products, and /cart map to specific components.

    Providing the Router

    In a modern standalone Angular application, the router can be provided during application bootstrap.

    typescript
    import { bootstrapApplication } from '@angular/platform-browser';
    import { provideRouter } from '@angular/router';
    import { AppComponent } from './app/app.component';
    import { routes } from './app/app.routes';
    bootstrapApplication(AppComponent, {
    providers: [provideRouter(routes)]
    });

    In module-based Angular applications, you may encounter RouterModule.forRoot().

    Understanding router-outlet

    Defining routes is not enough. Angular needs to know where routed components should appear.

    html
    <header>My Application</header>
    <nav>Navigation</nav>
    <main>
    <router-outlet />
    </main>
    <footer>Copyright</footer>

    Only the routed content changes; the surrounding application shell remains.

    Router Architecture

    Router Flow

    Browser URL to User View

    1
    Browser
    2
    URL
    3
    Angular Router
    4
    Route Configuration
    5
    Route Match
    6
    Component or Lazy Feature
    7
    router-outlet
    8
    User View

    For internal Angular routes, use routerLink.

    html
    <a routerLink="/">Home</a>
    <a routerLink="/products">Products</a>
    <a routerLink="/cart">Cart</a>

    Why Not Use href Everywhere?

    href performs normal browser navigation and may reload the app depending on usage. Use routerLink for internal Angular routes and regular href for external websites.

    Active Route Styling

    html
    <a
    routerLink="/products"
    routerLinkActive="active">
    Products
    </a>

    When the route is active, Angular applies the active CSS class.

    Programmatic Navigation

    Sometimes navigation happens because of application logic, such as after login or order completion.

    typescript
    import { Router } from '@angular/router';
    export class LoginComponent {
    constructor(private router: Router) {}
    login(): void {
    // Authentication logic
    this.router.navigate(['/dashboard']);
    }
    }

    Real-World Login Flow

    text
    User Opens Login
    /login
    Enters Credentials
    Authentication API
    ┌───┴────┐
    ▼ ▼
    Success Failure
    │ │
    ▼ ▼
    Navigate Show Error
    /dashboard

    Route Parameters

    Use route parameters for dynamic resources.

    typescript
    {
    path: 'products/:id',
    component: ProductDetailsComponent
    }

    URLs like /products/101 and /products/500 share the same route shape.

    Route Parameter Architecture

    text
    /products/101
    Angular Router
    products/:id
    id = 101
    ProductDetailsComponent
    Product Service
    Backend API

    Reading Route Parameters

    typescript
    import { ActivatedRoute } from '@angular/router';
    export class ProductDetailsComponent {
    constructor(private route: ActivatedRoute) {}
    ngOnInit(): void {
    const productId = this.route.snapshot.paramMap.get('id');
    console.log(productId);
    }
    }

    Snapshot vs Observable Route Parameters

    snapshot provides route state at a particular moment. The observable form is useful when parameters can change while Angular continues using the same component instance.

    typescript
    this.route.paramMap
    .subscribe(params => {
    const id = params.get('id');
    this.loadProduct(id);
    });

    Query Parameters

    Query parameters commonly represent optional view state such as filters, search terms, sorting, and pagination.

    text
    /products?category=laptop&page=2
    typescript
    this.router.navigate(
    ['/products'],
    {
    queryParams: {
    category: 'laptop',
    page: 2
    }
    }
    );

    Reading Query Parameters

    typescript
    this.route.queryParamMap
    .subscribe(params => {
    const category = params.get('category');
    const page = params.get('page');
    });

    Query parameters are especially useful for shareable search and filtering state.

    Route Parameters vs Query Parameters

    Route ParameterQuery Parameter
    /products/101/products?page=2
    Usually identifies a resourceUsually modifies a view
    Often requiredOften optional

    Route Redirects

    typescript
    {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
    }

    pathMatch: 'full' is important for empty-path redirects.

    Wildcard Routes and 404 Pages

    typescript
    {
    path: '**',
    component: NotFoundComponent
    }

    This route should normally appear at the end of the route configuration.

    Child Routes

    Large applications often contain nested sections.

    typescript
    {
    path: 'account',
    component: AccountComponent,
    children: [
    { path: 'profile', component: ProfileComponent },
    { path: 'security', component: SecurityComponent },
    { path: 'preferences', component: PreferencesComponent }
    ]
    }

    The parent component typically contains another <router-outlet /> for child routes.

    Nested Routing Architecture

    text
    AppComponent
    Main router-outlet
    AccountComponent
    ├── Account Navigation
    └── Child router-outlet
    ├── ProfileComponent
    ├── SecurityComponent
    └── PreferencesComponent

    Route Guards

    Route Guards participate in navigation decisions, such as authentication checks, role-based navigation, unsaved form warnings, feature access, and conditional navigation.

    text
    User Navigates
    Route Guard
    ┌───┴────┐
    ▼ ▼
    Allow Deny
    │ │
    ▼ ▼
    Route Redirect

    Authentication Guard Example

    typescript
    export const authGuard = () => {
    const authService = inject(AuthService);
    const router = inject(Router);
    if (authService.isLoggedIn()) {
    return true;
    }
    return router.createUrlTree(['/login']);
    };
    typescript
    {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [authGuard]
    }

    Important Security Principle

    Route Guards are useful for navigation and user experience, but they do not secure backend APIs.

    text
    Angular Route Guard -> Controls Frontend Navigation
    Backend Authorization -> Controls Actual Resource Access

    The backend must always enforce authorization independently.

    Lazy Loading

    As applications grow, loading every feature immediately can hurt startup performance. Lazy loading allows Angular to load feature code when it is needed.

    Lazy Loading Architecture

    text
    Application Starts
    Load Core Application
    User Opens Dashboard
    Dashboard Available
    User Opens Admin
    Load Admin Feature

    Lazy Loading a Standalone Component

    typescript
    {
    path: 'reports',
    loadComponent: () =>
    import('./reports/reports.component')
    .then(m => m.ReportsComponent)
    }

    Lazy Loading Feature Routes

    typescript
    {
    path: 'admin',
    loadChildren: () =>
    import('./admin/admin.routes')
    .then(m => m.ADMIN_ROUTES)
    }

    Enterprise Routing Architecture

    text
    App Router
    ├── Public Routes
    ├── Protected Routes
    ├── Lazy Features
    └── Admin Routes

    Large applications should organize routes by business feature instead of placing hundreds of routes in one file.

    Route Resolvers

    A resolver can load route-related data before a routed component is activated. Use resolvers thoughtfully: if loading takes a long time, displaying a loading state inside the page may be preferable.

    Unsaved Changes Protection

    Navigation guard patterns such as CanDeactivate can warn users before leaving forms with unsaved changes.

    text
    User Navigates Away
    Unsaved Changes?
    / \
    No Yes
    │ │
    ▼ ▼
    Navigate Ask User

    Route Data

    typescript
    {
    path: 'admin',
    component: AdminComponent,
    data: {
    title: 'Administration',
    requiredRole: 'ADMIN'
    }
    }

    Route data can support page titles, breadcrumbs, navigation metadata, and feature configuration. Metadata alone does not enforce security.

    Real-World Case Study: E-Commerce Routing

    text
    /
    /products
    /products/101
    /cart
    /checkout
    /orders
    /orders/5001
    /admin/products
    /admin/orders

    The router becomes the navigation backbone of the entire frontend.

    Routing and Authentication Flow

    text
    User Requests Protected Route
    Auth Guard
    ┌─────┴─────┐
    ▼ ▼
    Authenticated Not Authenticated
    │ │
    ▼ ▼
    Continue Redirect Login
    Login
    Authentication
    Navigate to Intended Route

    Routing and Browser Refresh

    If a user directly opens /products/101, the production web server must be configured to serve the Angular app entry point for appropriate client-side routes. Then Angular Router can process the URL after startup.

    Route Design Best Practices

    • Keep URLs meaningful.
    • Use query parameters for optional view state.
    • Lazy-load large features.
    • Use guards for navigation flow, but enforce authorization on the backend.
    • Add a 404 route.
    • Organize route configuration by feature.

    Common Pitfalls

    Putting the Wildcard Route First

    The wildcard can capture routes before intended routes are reached. Keep it last.

    Treating Route Guards as Security

    Frontend guards can be bypassed. Backend authorization is mandatory.

    Forgetting router-outlet

    Routes need an outlet where routed content can render.

    Overusing Snapshot Parameters

    If parameters can change while the same component remains active, use reactive route parameter APIs.

    Loading Every Feature Eagerly

    Use lazy loading strategically for large applications.

    Ignoring Server Configuration

    Client-side routing may work in development but fail on deep URL refreshes in production if hosting is not configured for SPA routing.

    Common Misconceptions

    Misconception

    Angular Router sends every navigation request to the backend.

    Reality

    Normal Angular SPA navigation is primarily handled client-side after the application has loaded.

    Misconception

    routerLink and href are always identical.

    Reality

    routerLink integrates with Angular Router for internal navigation, while href performs normal browser navigation.

    Misconception

    A Route Guard protects the backend.

    Reality

    Route Guards control frontend navigation. Backend APIs require independent authentication and authorization.

    Misconception

    Lazy loading means API data is lazy loaded.

    Reality

    Router lazy loading primarily concerns JavaScript application code. API data loading is separate.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    13 questions
    1BeginnerQuestionWhat is Angular Router?+

    Answer

    Angular Router maps browser URLs to application views and supports route parameters, nested routes, lazy loading, guards, redirects, and route data.
    2BeginnerQuestionWhat is router-outlet?+

    Answer

    router-outlet is the placeholder where Angular renders the component associated with the currently activated route.
    3BeginnerQuestionWhat is routerLink?+

    Answer

    routerLink is an Angular directive used for client-side navigation between application routes.
    4BeginnerQuestionWhat is the difference between routerLink and Router.navigate()?+

    Answer

    routerLink is declarative template navigation. Router.navigate() is programmatic navigation from TypeScript logic.
    5IntermediateQuestionWhat are route parameters?+

    Answer

    Route parameters are dynamic values embedded in a route path, such as /products/:id.
    6IntermediateQuestionWhat is the difference between route parameters and query parameters?+

    Answer

    Route parameters identify resources. Query parameters commonly represent optional state such as filters, sorting, or pagination.
    7IntermediateQuestionWhat is lazy loading?+

    Answer

    Lazy loading delays loading certain application code until the user navigates to the corresponding feature.
    8IntermediateQuestionWhat are Route Guards?+

    Answer

    Route Guards participate in navigation decisions, such as whether a route can be activated or whether a user can leave a route.
    9AdvancedQuestionWhat is a wildcard route?+

    Answer

    A wildcard route uses ** to match URLs that have not matched previous routes and is commonly used for a 404 page.
    10AdvancedQuestionWhy should the wildcard route usually be last?+

    Answer

    Because it can broadly match otherwise unmatched URLs and prevent intended routes from being reached if placed too early.
    11AdvancedQuestionWhat is the difference between eager loading and lazy loading?+

    Answer

    Eager loading includes feature code in the initial loading path. Lazy loading defers feature code until needed.
    12AdvancedQuestionWhat happens when a user refreshes a deep Angular route?+

    Answer

    The browser sends the URL to the server. The server must return the Angular app entry point so Angular Router can process the URL after startup.
    13AdvancedQuestionHow would you design routing for a large enterprise application?+

    Answer

    Organize routes by business feature, lazy-load large feature areas, use nested routes for nested layouts, route params for resource identities, query params for shareable filter state, guards for navigation control, and backend APIs for actual authorization.

    Summary

    Angular Router connects the browser URL with the application's user interface.

    text
    URL
    Angular Router
    Route Configuration
    Component
    router-outlet

    In production applications, routing defines how users navigate, bookmark, share, access, and experience different areas of the application.

    When combined with meaningful URLs, lazy loading, feature-based route organization, route parameters, query parameters, guards, and proper backend authorization, Angular Router provides the foundation for scalable Single Page Applications.

    Next Lesson: Angular Services & Dependency Injection - you'll learn how Angular separates business logic from components, how services share data across the application, how Dependency Injection works internally, how providedIn: 'root' creates application-level services, how hierarchical injectors work, and how enterprise Angular applications structure API, domain, state, and utility services.

    Ready to mark this lesson complete?Track your journey across the entire course.