Skip to main content

Router Class

The Router service is the main entry point for Angular routing. It provides methods for navigation, URL manipulation, and access to routing state.

Import

import { Router } from '@angular/router';

Class Overview

class Router {
  // Properties
  events: Observable<Event>;
  routerState: RouterState;
  url: string;
  navigated: boolean;
  config: Routes;
  currentNavigation: Signal<Navigation | null>;
  lastSuccessfulNavigation: Signal<Navigation | null>;

  // Navigation Methods
  navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
  navigateByUrl(url: string | UrlTree, extras?: NavigationBehaviorOptions): Promise<boolean>;

  // URL Manipulation
  createUrlTree(commands: any[], navigationExtras?: UrlCreationOptions): UrlTree;
  serializeUrl(url: UrlTree): string;
  parseUrl(url: string): UrlTree;
  isActive(url: string | UrlTree, matchOptions: IsActiveMatchOptions): boolean;

  // Configuration
  resetConfig(config: Routes): void;

  // Lifecycle
  initialNavigation(): void;
  setUpLocationChangeListener(): void;
  dispose(): void;
}

Description

The Router service facilitates navigation among views and URL manipulation in Angular applications. It is provided in the root scope and configured using provideRouter or RouterModule.forRoot().
The Router service is automatically provided when you use provideRouter() in standalone apps or RouterModule.forRoot() in NgModule-based apps.

Properties

events

readonly events: Observable<Event>
An observable stream of routing events. Subscribe to this to react to navigation lifecycle events. Example:
import { Component, inject, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';

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

  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        console.log('Navigation started to:', event.url);
      }
      if (event instanceof NavigationEnd) {
        console.log('Navigation completed to:', event.url);
      }
      if (event instanceof NavigationError) {
        console.error('Navigation error:', event.error);
      }
    });
  }
}
Event Types:
  • NavigationStart - Navigation begins
  • RoutesRecognized - Routes matched
  • GuardsCheckStart - Guards execution begins
  • GuardsCheckEnd - Guards execution completes
  • ResolveStart - Resolvers execution begins
  • ResolveEnd - Resolvers execution completes
  • NavigationEnd - Navigation succeeds
  • NavigationCancel - Navigation cancelled
  • NavigationError - Navigation fails

routerState

readonly routerState: RouterState
The current router state containing the activated route tree and routing information. Example:
const router = inject(Router);
const currentUrl = router.routerState.snapshot.url;
const rootRoute = router.routerState.root;

url

readonly url: string
The current URL as a string. Example:
const router = inject(Router);
console.log('Current URL:', router.url); // e.g., "/users/123"
navigated: boolean
Indicates whether at least one navigation event has occurred. false initially, true after first navigation.

config

config: Routes
The current route configuration array. Example:
const router = inject(Router);
console.log('Current routes:', router.config);

currentNavigation

readonly currentNavigation: Signal<Navigation | null>
A signal that represents the current navigation object when navigating, null when idle. Example:
import { Component, inject, effect } from '@angular/core';
import { Router } from '@angular/router';

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

  constructor() {
    effect(() => {
      const nav = this.router.currentNavigation();
      if (nav) {
        console.log('Navigating to:', nav.finalUrl);
      }
    });
  }
}

lastSuccessfulNavigation

readonly lastSuccessfulNavigation: Signal<Navigation | null>
A signal representing the most recent successful navigation, null if no navigation has succeeded yet.

Methods

navigate(
  commands: any[],
  extras?: NavigationExtras
): Promise<boolean>
Navigates based on the provided array of commands and options. Parameters:
commands
any[]
required
Array of URL fragments to construct the target URL. Can include path segments, parameters, and outlets.
extras
NavigationExtras
Options that control navigation behavior:
  • relativeTo - Route to navigate relative to
  • queryParams - Query parameters for the URL
  • fragment - URL fragment/hash
  • queryParamsHandling - How to handle query params ('merge', 'preserve', or 'replace')
  • skipLocationChange - Navigate without updating browser URL
  • replaceUrl - Replace current history entry instead of pushing new one
  • state - Developer-defined state to pass with navigation
Returns: Promise that resolves to true on success, false on failure. Examples:
import { Component, inject } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

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

  // Absolute navigation
  goToHome() {
    this.router.navigate(['/home']);
  }

  // Navigation with parameters
  viewUser(userId: number) {
    this.router.navigate(['/users', userId]);
  }

  // Navigation with query params and fragment
  searchProducts(query: string) {
    this.router.navigate(['/products'], {
      queryParams: { q: query, page: 1 },
      fragment: 'results'
    });
  }

  // Relative navigation
  goToDetails() {
    this.router.navigate(['details'], { relativeTo: this.route });
  }

  // Navigate with matrix parameters
  viewProductWithOptions(id: number) {
    this.router.navigate(['/products', id, { color: 'blue', size: 'large' }]);
  }

  // Navigate to named outlet
  openSidebar() {
    this.router.navigate([{
      outlets: { sidebar: ['messages'] }
    }]);
  }
}
navigateByUrl(
  url: string | UrlTree,
  extras?: NavigationBehaviorOptions
): Promise<boolean>
Navigates to a view using an absolute URL path or UrlTree. Parameters:
url
string | UrlTree
required
Absolute URL path or UrlTree object.
extras
NavigationBehaviorOptions
Options controlling navigation behavior:
  • skipLocationChange - Don’t update browser URL
  • replaceUrl - Replace history entry
  • state - State to pass with navigation
  • onSameUrlNavigation - How to handle navigation to current URL
Returns: Promise that resolves to true on success, false on failure. Examples:
const router = inject(Router);

// Navigate to absolute URL
router.navigateByUrl('/users/123');

// Navigate without updating browser URL
router.navigateByUrl('/admin/settings', {
  skipLocationChange: true
});

// Navigate and replace history entry
router.navigateByUrl('/dashboard', {
  replaceUrl: true
});

// Navigate with state
router.navigateByUrl('/confirmation', {
  state: { orderId: '12345', total: 99.99 }
});

createUrlTree()

createUrlTree(
  commands: any[],
  navigationExtras?: UrlCreationOptions
): UrlTree
Creates a UrlTree object from an array of commands without navigating. Parameters:
commands
any[]
required
Array of URL fragments.
navigationExtras
UrlCreationOptions
Options for URL creation including relativeTo, queryParams, fragment, etc.
Returns: A UrlTree object. Examples:
const router = inject(Router);

// Create URL tree
const urlTree = router.createUrlTree(['/users', 123]);

// Create URL tree with query params
const searchUrl = router.createUrlTree(['/products'], {
  queryParams: { category: 'electronics' }
});

// Use in route guard to redirect
import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';

export const authGuard: CanActivateFn = () => {
  const router = inject(Router);
  const isLoggedIn = checkAuth(); // your auth logic

  if (!isLoggedIn) {
    return router.createUrlTree(['/login']);
  }
  return true;
};

serializeUrl()

serializeUrl(url: UrlTree): string
Converts a UrlTree to a string URL. Example:
const router = inject(Router);
const urlTree = router.createUrlTree(['/users', 123]);
const urlString = router.serializeUrl(urlTree);
console.log(urlString); // "/users/123"

parseUrl()

parseUrl(url: string): UrlTree
Parses a string URL into a UrlTree object. Example:
const router = inject(Router);
const urlTree = router.parseUrl('/users/123?tab=profile#bio');
console.log(urlTree.fragment); // "bio"
console.log(urlTree.queryParams); // { tab: 'profile' }

isActive()

isActive(
  url: string | UrlTree,
  matchOptions: IsActiveMatchOptions
): boolean
Checks if a given URL is currently active. Parameters:
url
string | UrlTree
required
URL to check.
matchOptions
IsActiveMatchOptions
required
Matching options:
  • paths - 'exact' or 'subset'
  • queryParams - 'exact', 'subset', or 'ignored'
  • fragment - 'exact' or 'ignored'
  • matrixParams - 'exact', 'subset', or 'ignored'
Returns: true if URL is active, false otherwise. Example:
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

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

  isHomeActive(): boolean {
    return this.router.isActive('/home', {
      paths: 'exact',
      queryParams: 'ignored',
      fragment: 'ignored',
      matrixParams: 'ignored'
    });
  }
}
The isActive method is deprecated in favor of using the standalone isActive function from @angular/router.

resetConfig()

resetConfig(config: Routes): void
Resets the route configuration. Useful for dynamic route updates. Example:
const router = inject(Router);

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

router.resetConfig(newRoutes);

initialNavigation()

initialNavigation(): void
Performs the initial navigation. Called automatically by the Router during application bootstrap.

setUpLocationChangeListener()

setUpLocationChangeListener(): void
Sets up the listener for browser location changes (back/forward buttons).

dispose()

dispose(): void
Disposes of the router, cleaning up subscriptions and event listeners.

Usage Examples

Basic Navigation

import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-nav',
  template: `
    <button (click)="goHome()">Home</button>
    <button (click)="goToUser(42)">User 42</button>
  `
})
export class NavComponent {
  private router = inject(Router);

  goHome() {
    this.router.navigate(['/home']);
  }

  goToUser(id: number) {
    this.router.navigate(['/users', id]);
  }
}
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

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

  search(term: string) {
    this.router.navigate(['/results'], {
      queryParams: { q: term },
      queryParamsHandling: 'merge' // Merge with existing params
    });
  }

  saveAndNavigate() {
    // Save changes...
    this.router.navigate(['/dashboard'], {
      replaceUrl: true, // Don't add to history
      state: { message: 'Changes saved successfully' }
    });
  }
}

Listening to Navigation Events

import { Component, inject, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

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

  ngOnInit() {
    // Track page views
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      // Send to analytics service
      console.log('Page view:', event.urlAfterRedirects);
    });
  }
}

Using UrlTree for Redirects

import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';

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

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

  // Create URL tree to redirect to login with return URL
  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url }
  });
};

See Also

Route Configuration

Learn about configuring routes

Route Guards

Protect routes with guards

Routing Guide

Complete routing guide

Navigation Events

Router event types and usage