> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/angular/angular/llms.txt
> Use this file to discover all available pages before exploring further.

# Router Class

> API reference for the Angular Router service - the main entry point for navigation and routing.

# 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

```typescript theme={null}
import { Router } from '@angular/router';
```

## Class Overview

```typescript theme={null}
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()`.

<Note>
  The Router service is automatically provided when you use `provideRouter()` in standalone apps or `RouterModule.forRoot()` in NgModule-based apps.
</Note>

## Properties

### events

```typescript theme={null}
readonly events: Observable<Event>
```

An observable stream of routing events. Subscribe to this to react to navigation lifecycle events.

**Example:**

```typescript theme={null}
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

```typescript theme={null}
readonly routerState: RouterState
```

The current router state containing the activated route tree and routing information.

**Example:**

```typescript theme={null}
const router = inject(Router);
const currentUrl = router.routerState.snapshot.url;
const rootRoute = router.routerState.root;
```

### url

```typescript theme={null}
readonly url: string
```

The current URL as a string.

**Example:**

```typescript theme={null}
const router = inject(Router);
console.log('Current URL:', router.url); // e.g., "/users/123"
```

### navigated

```typescript theme={null}
navigated: boolean
```

Indicates whether at least one navigation event has occurred. `false` initially, `true` after first navigation.

### config

```typescript theme={null}
config: Routes
```

The current route configuration array.

**Example:**

```typescript theme={null}
const router = inject(Router);
console.log('Current routes:', router.config);
```

### currentNavigation

```typescript theme={null}
readonly currentNavigation: Signal<Navigation | null>
```

A signal that represents the current navigation object when navigating, `null` when idle.

**Example:**

```typescript theme={null}
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

```typescript theme={null}
readonly lastSuccessfulNavigation: Signal<Navigation | null>
```

A signal representing the most recent successful navigation, `null` if no navigation has succeeded yet.

## Methods

### navigate()

```typescript theme={null}
navigate(
  commands: any[],
  extras?: NavigationExtras
): Promise<boolean>
```

Navigates based on the provided array of commands and options.

**Parameters:**

<ParamField path="commands" type="any[]" required>
  Array of URL fragments to construct the target URL. Can include path segments, parameters, and outlets.
</ParamField>

<ParamField path="extras" type="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
</ParamField>

**Returns:** Promise that resolves to `true` on success, `false` on failure.

**Examples:**

```typescript theme={null}
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()

```typescript theme={null}
navigateByUrl(
  url: string | UrlTree,
  extras?: NavigationBehaviorOptions
): Promise<boolean>
```

Navigates to a view using an absolute URL path or UrlTree.

**Parameters:**

<ParamField path="url" type="string | UrlTree" required>
  Absolute URL path or UrlTree object.
</ParamField>

<ParamField path="extras" type="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
</ParamField>

**Returns:** Promise that resolves to `true` on success, `false` on failure.

**Examples:**

```typescript theme={null}
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()

```typescript theme={null}
createUrlTree(
  commands: any[],
  navigationExtras?: UrlCreationOptions
): UrlTree
```

Creates a UrlTree object from an array of commands without navigating.

**Parameters:**

<ParamField path="commands" type="any[]" required>
  Array of URL fragments.
</ParamField>

<ParamField path="navigationExtras" type="UrlCreationOptions">
  Options for URL creation including `relativeTo`, `queryParams`, `fragment`, etc.
</ParamField>

**Returns:** A `UrlTree` object.

**Examples:**

```typescript theme={null}
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()

```typescript theme={null}
serializeUrl(url: UrlTree): string
```

Converts a UrlTree to a string URL.

**Example:**

```typescript theme={null}
const router = inject(Router);
const urlTree = router.createUrlTree(['/users', 123]);
const urlString = router.serializeUrl(urlTree);
console.log(urlString); // "/users/123"
```

### parseUrl()

```typescript theme={null}
parseUrl(url: string): UrlTree
```

Parses a string URL into a UrlTree object.

**Example:**

```typescript theme={null}
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()

```typescript theme={null}
isActive(
  url: string | UrlTree,
  matchOptions: IsActiveMatchOptions
): boolean
```

Checks if a given URL is currently active.

**Parameters:**

<ParamField path="url" type="string | UrlTree" required>
  URL to check.
</ParamField>

<ParamField path="matchOptions" type="IsActiveMatchOptions" required>
  Matching options:

  * `paths` - `'exact'` or `'subset'`
  * `queryParams` - `'exact'`, `'subset'`, or `'ignored'`
  * `fragment` - `'exact'` or `'ignored'`
  * `matrixParams` - `'exact'`, `'subset'`, or `'ignored'`
</ParamField>

**Returns:** `true` if URL is active, `false` otherwise.

**Example:**

```typescript theme={null}
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'
    });
  }
}
```

<Note>
  The `isActive` method is deprecated in favor of using the standalone `isActive` function from `@angular/router`.
</Note>

### resetConfig()

```typescript theme={null}
resetConfig(config: Routes): void
```

Resets the route configuration. Useful for dynamic route updates.

**Example:**

```typescript theme={null}
const router = inject(Router);

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

router.resetConfig(newRoutes);
```

### initialNavigation()

```typescript theme={null}
initialNavigation(): void
```

Performs the initial navigation. Called automatically by the Router during application bootstrap.

### setUpLocationChangeListener()

```typescript theme={null}
setUpLocationChangeListener(): void
```

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

### dispose()

```typescript theme={null}
dispose(): void
```

Disposes of the router, cleaning up subscriptions and event listeners.

## Usage Examples

### Basic Navigation

```typescript theme={null}
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]);
  }
}
```

### Navigation with Options

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

<CardGroup cols={2}>
  <Card title="Route Configuration" icon="route" href="/api/router/route-config">
    Learn about configuring routes
  </Card>

  <Card title="Route Guards" icon="shield" href="/api/router/guards">
    Protect routes with guards
  </Card>

  <Card title="Routing Guide" icon="book" href="/routing/router-overview">
    Complete routing guide
  </Card>

  <Card title="Navigation Events" icon="bolt" href="/routing/router-overview">
    Router event types and usage
  </Card>
</CardGroup>
