What is the Router?
The Angular Router is a core service that:- Maps URL paths to components
- Manages browser history and navigation
- Handles route parameters and query parameters
- Supports lazy loading of feature modules
- Provides navigation guards for access control
- Resolves data before route activation
Router Setup
There are two ways to configure the router in Angular: usingprovideRouter (standalone) or RouterModule (module-based).
Standalone Setup (Recommended)
The modern approach usesprovideRouter with the standalone API:
main.ts
The
provideRouter function is defined in packages/router/src/provide_router.ts:99 and sets up all necessary router services.Module-Based Setup
For applications using NgModules:app.module.ts
Router Configuration Options
You can customize router behavior with additional features:main.ts
The Router Service
TheRouter service provides methods for programmatic navigation:
component.ts
Router Properties
The Router service exposes several useful properties:Router Outlet
The<router-outlet> directive marks where the router should display views:
app.component.html
Named Outlets
You can use multiple outlets to display different content simultaneously:routes.ts
RouterLink Directive
TherouterLink directive creates navigation links:
RouterLinkActive
Highlight active links automatically:Navigation Events
The router emits events during navigation:Navigation events are defined in
packages/router/src/events.ts and include NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized, and more.Best Practices
Use provideRouter
Prefer the standalone
provideRouter API for new applications. It’s more modern and tree-shakeable.Lazy Load Modules
Use lazy loading for feature modules to reduce initial bundle size and improve load times.
Type-Safe Routes
Define routes in a separate file and export them for better maintainability and type safety.
Handle Errors
Subscribe to navigation errors and provide user-friendly error messages.
Next Steps
Defining Routes
Learn how to define routes with paths, parameters, and nested routes
Route Guards
Protect routes with guards to control access and navigation
Lazy Loading
Implement lazy loading to optimize your application’s performance
