or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mddirectives.mdindex.mdnavigation-state.mdroute-config.mdrouting-core.mdurl-handling.md
tile.json

tessl/npm-angular--router

Angular Router provides declarative routing with URL synchronization, lazy loading, and advanced navigation features for single-page applications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@angular/router@20.2.x

To install, run

npx @tessl/cli install tessl/npm-angular--router@20.2.0

index.mddocs/

Angular Router

Angular Router provides declarative routing with URL synchronization, lazy loading, and advanced navigation features for single-page applications. It manages navigation between views, handles URL parsing and generation, supports route guards and resolvers, and provides powerful APIs for programmatic navigation.

Package Information

  • Package Name: @angular/router
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @angular/router

Core Imports

import { Router, ActivatedRoute, RouterOutlet, RouterLink } from '@angular/router';
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { Routes, Route, NavigationExtras } from '@angular/router';

For standalone applications:

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)
  ]
});

For NgModule-based applications:

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

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  // ...
})
export class AppModule {}

Basic Usage

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { RouterOutlet, RouterLink } from '@angular/router';

// Define routes
export const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users/:id', component: UserComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', redirectTo: '' }
];

// Component using router services
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  template: `
    <nav>
      <a routerLink="/">Home</a>
      <a routerLink="/about">About</a>
      <a [routerLink]="['/users', userId]">User Profile</a>
    </nav>
    <router-outlet></router-outlet>
  `
})
export class AppComponent {
  userId = 123;
  
  constructor(private router: Router, private route: ActivatedRoute) {}
  
  // Programmatic navigation
  navigateToUser(id: number) {
    this.router.navigate(['/users', id]);
  }
  
  // Navigation with extras
  navigateWithOptions() {
    this.router.navigate(['/users', this.userId], {
      queryParams: { tab: 'profile' },
      fragment: 'details'
    });
  }
}

// Component accessing route data
@Component({
  selector: 'app-user',
  template: `<h1>User {{userId}}</h1>`
})
export class UserComponent implements OnInit {
  userId: string;
  
  constructor(private route: ActivatedRoute) {}
  
  ngOnInit() {
    this.userId = this.route.snapshot.paramMap.get('id')!;
    
    // Or subscribe to changes
    this.route.paramMap.subscribe(params => {
      this.userId = params.get('id')!;
    });
  }
}

Architecture

Angular Router is built around several key components that work together to provide declarative routing:

  • Router Service: Core navigation engine that manages route transitions, URL parsing, and route matching
  • Route Configuration: Declarative route definitions with path patterns, components, guards, and metadata
  • Navigation State: Tree structure representing current route state with ActivatedRoute nodes containing route data
  • Router Directives: Template directives like RouterOutlet, RouterLink, and RouterLinkActive for UI integration
  • URL Management: URL tree representation and serialization with UrlTree and UrlSerializer classes
  • Navigation Events: Observable stream of navigation lifecycle events for tracking routing state
  • Route Guards: Functional and class-based guards for controlling route activation, deactivation, and loading
  • Data Resolvers: Pre-route-activation data fetching mechanism for loading required data
  • Advanced Strategies: Pluggable strategies for route reuse, preloading, and title management

Capabilities

Core Routing

Core router functionality including navigation methods, route matching, and basic routing setup. Essential for all routing implementations.

class Router {
  navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
  navigateByUrl(url: string | UrlTree, extras?: NavigationBehaviorOptions): Promise<boolean>;
  createUrlTree(commands: any[], navigationExtras?: UrlCreationOptions): UrlTree;
  isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean;
  events: Observable<Event>;
  routerState: RouterState;
  url: string;
  config: Routes;
}

Core Routing

Route Configuration

Route definitions, configuration options, guards, and resolvers for declarative routing setup.

interface Route {
  path?: string;
  pathMatch?: 'prefix' | 'full';
  component?: Type<any>;
  loadComponent?: () => Type<unknown> | Observable<Type<unknown>> | Promise<Type<unknown>>;
  canActivate?: Array<CanActivateFn | DeprecatedGuard>;
  canMatch?: Array<CanMatchFn | DeprecatedGuard>;
  resolve?: ResolveData;
  children?: Routes;
  data?: Data;
}

type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => MaybeAsync<GuardResult>;
type ResolveFn<T> = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => MaybeAsync<T | RedirectCommand>;

Route Configuration

Navigation & State

Route state management, navigation events, and accessing current route information.

class ActivatedRoute {
  url: Observable<UrlSegment[]>;
  params: Observable<Params>;
  queryParams: Observable<Params>;
  fragment: Observable<string | null>;
  data: Observable<Data>;
  paramMap: Observable<ParamMap>;
  queryParamMap: Observable<ParamMap>;
  snapshot: ActivatedRouteSnapshot;
  routeConfig: Route | null;
}

class RouterState extends Tree<ActivatedRoute> {
  snapshot: RouterStateSnapshot;
}

type Event = NavigationStart | NavigationEnd | NavigationCancel | NavigationError | 
             RoutesRecognized | GuardsCheckStart | GuardsCheckEnd | ResolveStart | ResolveEnd;

Navigation & State

Router Directives

Template directives for integrating routing into Angular templates and managing route-based UI updates.

@Directive({ selector: 'router-outlet' })
class RouterOutlet {
  name: string;
  isActivated: boolean;
  component: Object;
  activatedRoute: ActivatedRoute;
  activateEvents: EventEmitter<any>;
  deactivateEvents: EventEmitter<any>;
}

@Directive({ selector: '[routerLink]' })
class RouterLink {
  routerLink: readonly any[] | string | UrlTree | null | undefined;
  queryParams?: Params | null;
  fragment?: string;
  relativeTo?: ActivatedRoute | null;
}

@Directive({ selector: '[routerLinkActive]' })
class RouterLinkActive {
  routerLinkActive: string[] | string;
  isActive: boolean;
  isActiveChange: EventEmitter<boolean>;
}

Router Directives

URL Handling

URL parsing, tree representation, serialization, and URL management utilities.

class UrlTree {
  root: UrlSegmentGroup;
  queryParams: Params;
  fragment: string | null;
  queryParamMap: ParamMap;
}

class UrlSegment {
  path: string;
  parameters: {[name: string]: string};
  parameterMap: ParamMap;
}

abstract class UrlSerializer {
  abstract parse(url: string): UrlTree;
  abstract serialize(tree: UrlTree): string;
}

URL Handling

Advanced Features

Advanced routing features including preloading strategies, route reuse, title management, and module configuration.

function provideRouter(routes: Routes, ...features: RouterFeatures[]): EnvironmentProviders;

function withPreloading(preloadingStrategy: Type<PreloadingStrategy>): PreloadingFeature;
function withComponentInputBinding(): ComponentInputBindingFeature;
function withViewTransitions(options?: ViewTransitionsFeatureOptions): ViewTransitionsFeature;

abstract class PreloadingStrategy {
  abstract preload(route: Route, fn: () => Observable<any>): Observable<any>;
}

abstract class RouteReuseStrategy {
  abstract shouldDetach(route: ActivatedRouteSnapshot): boolean;
  abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
  abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}

abstract class TitleStrategy {
  abstract updateTitle(snapshot: RouterStateSnapshot): void;
  buildTitle(snapshot: RouterStateSnapshot): string | undefined;
}

Advanced Features

Types

type Routes = Route[];
type MaybeAsync<T> = T | Observable<T> | Promise<T>;
type GuardResult = boolean | UrlTree | RedirectCommand;
type Data = {[key: string | symbol]: any};
type Params = {[key: string]: any};

interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {}

interface UrlCreationOptions {
  relativeTo?: ActivatedRoute | null;
  queryParams?: Params | null;
  fragment?: string | null;
  queryParamsHandling?: QueryParamsHandling | null;
  preserveFragment?: boolean;
}

interface NavigationBehaviorOptions {
  onSameUrlNavigation?: OnSameUrlNavigation;
  skipLocationChange?: boolean;
  replaceUrl?: boolean;
  state?: {[k: string]: any};
  info?: unknown;
  browserUrl?: string | UrlTree;
}

interface ParamMap {
  has(name: string): boolean;
  get(name: string): string | null;
  getAll(name: string): string[];
  readonly keys: string[];
}

class RedirectCommand {
  constructor(redirectTo: UrlTree, navigationBehaviorOptions?: NavigationBehaviorOptions);
}

type OnSameUrlNavigation = 'reload' | 'ignore';
type QueryParamsHandling = 'merge' | 'preserve' | 'replace' | '';
type RunGuardsAndResolvers = 'pathParamsChange' | 'pathParamsOrQueryParamsChange' | 'paramsChange' | 'paramsOrQueryParamsChange' | 'always' | ((from: ActivatedRouteSnapshot, to: ActivatedRouteSnapshot) => boolean);