Skip to main content

Router Package Overview

The @angular/router package provides a complete navigation and routing solution for Angular applications. It enables you to map URLs to application views, handle navigation events, and manage browser history.

Core Concepts

The Router package is built around several key concepts:

Router Service

The Router service is the main entry point for navigation. It provides methods to:
  • Navigate to routes programmatically
  • Parse and serialize URLs
  • Track navigation state
  • Listen to routing events

Router Class

Core service for handling navigation and URL management

Route Configuration

Routes are defined using the Routes type, an array of Route objects that specify:
  • URL paths and patterns
  • Components to render
  • Child routes
  • Guards and resolvers
  • Lazy loading configuration

Route Configuration

Define your application’s routing structure

Route Guards

Guards control access to routes and can:
  • Prevent unauthorized navigation
  • Confirm navigation away from unsaved changes
  • Preload data before activating routes
  • Conditionally match routes

Route Guards

Protect routes with guard functions and interfaces

Installation

The Router package is included with Angular. To use it, import from @angular/router:
import { Router, Routes, provideRouter } from '@angular/router';

Setting Up Routing

Standalone Applications

For standalone applications, use provideRouter in your application configuration:
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)
  ]
});

NgModule Applications

For NgModule-based applications, import RouterModule:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Key Features

Programmatic Navigation

Navigate imperatively using the Router service:
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({ /* ... */ })
export class MyComponent {
  private router = inject(Router);

  navigateToUser(id: number) {
    this.router.navigate(['/users', id]);
  }
}

Route Parameters

Access route parameters using ActivatedRoute:
import { Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({ /* ... */ })
export class UserComponent implements OnInit {
  private route = inject(ActivatedRoute);

  ngOnInit() {
    const userId = this.route.snapshot.params['id'];
    // Or subscribe to parameter changes:
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
  }
}

Lazy Loading

Improve application performance by lazy loading feature modules:
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
  }
];
Listen to routing events:
import { Router, NavigationStart, NavigationEnd } from '@angular/router';

const router = inject(Router);

router.events.subscribe(event => {
  if (event instanceof NavigationStart) {
    console.log('Navigation started:', event.url);
  }
  if (event instanceof NavigationEnd) {
    console.log('Navigation completed:', event.url);
  }
});

Router Directives

The Router package includes directives for template-based navigation: Create navigation links in templates:
<a routerLink="/home">Home</a>
<a [routerLink]="['/users', userId]">User Profile</a>

RouterOutlet

Define where routed components should be rendered:
<router-outlet></router-outlet>

RouterLinkActive

Apply CSS classes to active links:
<a routerLink="/home" routerLinkActive="active">Home</a>

Common Patterns

Child Routes

Organize routes hierarchically:
const routes: Routes = [
  {
    path: 'products',
    component: ProductsComponent,
    children: [
      { path: '', component: ProductListComponent },
      { path: ':id', component: ProductDetailComponent },
      { path: ':id/edit', component: ProductEditComponent }
    ]
  }
];

Route Guards

Protect routes with functional guards:
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.isLoggedIn()) {
    return true;
  }

  return router.parseUrl('/login');
};

Data Resolvers

Preload data before route activation:
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from './user.service';

export const userResolver: ResolveFn<User> = (
  route: ActivatedRouteSnapshot
) => {
  const userService = inject(UserService);
  return userService.getUser(route.params['id']);
};

// In route configuration:
const routes: Routes = [
  {
    path: 'users/:id',
    component: UserComponent,
    resolve: { user: userResolver }
  }
];

API Reference

Router Class

Core Router service API

Route Configuration

Routes and Route interface

Route Guards

Guard functions and interfaces

Learn More

Routing Guide

Complete guide to routing in Angular

Common Router Tasks

Step-by-step routing tutorials

Build docs developers (and LLMs) love