Skip to main content
The Angular Router enables navigation from one view to the next as users perform tasks in your application. It interprets browser URL changes as instructions to navigate to a client-generated view and can pass optional parameters to the view component.

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: using provideRouter (standalone) or RouterModule (module-based). The modern approach uses provideRouter 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
Use RouterModule.forRoot() only in the root module. For feature modules, use RouterModule.forChild() instead.

Router Configuration Options

You can customize router behavior with additional features:
main.ts

The Router Service

The Router 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
The routerLink directive creates navigation links:

RouterLinkActive

Highlight active links automatically:
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