> ## 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 Package Overview

> Complete reference for the Angular Router package - navigation, routing configuration, and URL management.

# 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

The `Router` 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

<Card title="Router Class" icon="code" href="/api/router/router-class">
  Core service for handling navigation and URL management
</Card>

### Route Configuration

Routes are defined using the `Routes` type, an array of `Route` objects that specify:

* URL paths and patterns
* Components to render
* Child routes
* Guards and resolvers
* Lazy loading configuration

<Card title="Route Configuration" icon="route" href="/api/router/route-config">
  Define your application's routing structure
</Card>

### 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

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

## Installation

The Router package is included with Angular. To use it, import from `@angular/router`:

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

## Setting Up Routing

### Standalone Applications

For standalone applications, use `provideRouter` in your application configuration:

```typescript theme={null}
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes)
  ]
});
```

### NgModule Applications

For NgModule-based applications, import `RouterModule`:

```typescript theme={null}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
```

## Key Features

### Programmatic Navigation

Navigate imperatively using the Router service:

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

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

  navigateToUser(id: number) {
    this.router.navigate(['/users', id]);
  }
}
```

### Route Parameters

Access route parameters using `ActivatedRoute`:

```typescript theme={null}
import { Component, inject, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({ /* ... */ })
export class UserComponent implements OnInit {
  private route = inject(ActivatedRoute);

  ngOnInit() {
    const userId = this.route.snapshot.params['id'];
    // Or subscribe to parameter changes:
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
  }
}
```

### Lazy Loading

Improve application performance by lazy loading feature modules:

```typescript theme={null}
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
  }
];
```

### Navigation Events

Listen to routing events:

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

const router = inject(Router);

router.events.subscribe(event => {
  if (event instanceof NavigationStart) {
    console.log('Navigation started:', event.url);
  }
  if (event instanceof NavigationEnd) {
    console.log('Navigation completed:', event.url);
  }
});
```

## Router Directives

The Router package includes directives for template-based navigation:

### RouterLink

Create navigation links in templates:

```html theme={null}
<a routerLink="/home">Home</a>
<a [routerLink]="['/users', userId]">User Profile</a>
```

### RouterOutlet

Define where routed components should be rendered:

```html theme={null}
<router-outlet></router-outlet>
```

### RouterLinkActive

Apply CSS classes to active links:

```html theme={null}
<a routerLink="/home" routerLinkActive="active">Home</a>
```

## Common Patterns

### Child Routes

Organize routes hierarchically:

```typescript theme={null}
const routes: Routes = [
  {
    path: 'products',
    component: ProductsComponent,
    children: [
      { path: '', component: ProductListComponent },
      { path: ':id', component: ProductDetailComponent },
      { path: ':id/edit', component: ProductEditComponent }
    ]
  }
];
```

### Route Guards

Protect routes with functional guards:

```typescript theme={null}
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

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

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

  return router.parseUrl('/login');
};
```

### Data Resolvers

Preload data before route activation:

```typescript theme={null}
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from './user.service';

export const userResolver: ResolveFn<User> = (
  route: ActivatedRouteSnapshot
) => {
  const userService = inject(UserService);
  return userService.getUser(route.params['id']);
};

// In route configuration:
const routes: Routes = [
  {
    path: 'users/:id',
    component: UserComponent,
    resolve: { user: userResolver }
  }
];
```

## API Reference

<CardGroup cols={2}>
  <Card title="Router Class" icon="code" href="/api/router/router-class">
    Core Router service API
  </Card>

  <Card title="Route Configuration" icon="route" href="/api/router/route-config">
    Routes and Route interface
  </Card>

  <Card title="Route Guards" icon="shield" href="/api/router/guards">
    Guard functions and interfaces
  </Card>
</CardGroup>

## Learn More

<CardGroup cols={2}>
  <Card title="Routing Guide" icon="book" href="/routing/router-overview">
    Complete guide to routing in Angular
  </Card>

  <Card title="Common Router Tasks" icon="tasks" href="/routing/router-overview">
    Step-by-step routing tutorials
  </Card>
</CardGroup>
