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
TheRouter 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 theRoutes 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:
Setting Up Routing
Standalone Applications
For standalone applications, useprovideRouter in your application configuration:
NgModule Applications
For NgModule-based applications, importRouterModule:
Key Features
Programmatic Navigation
Navigate imperatively using the Router service:Route Parameters
Access route parameters usingActivatedRoute:
Lazy Loading
Improve application performance by lazy loading feature modules:Navigation Events
Listen to routing events:Router Directives
The Router package includes directives for template-based navigation:RouterLink
Create navigation links in templates:RouterOutlet
Define where routed components should be rendered:RouterLinkActive
Apply CSS classes to active links:Common Patterns
Child Routes
Organize routes hierarchically:Route Guards
Protect routes with functional guards:Data Resolvers
Preload data before route activation: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
