Core router functionality including the main Router service, navigation methods, route matching, and basic routing setup. Essential for all routing implementations.
The main router service that facilitates navigation and URL manipulation. Central hub for all routing operations.
/**
* Main router service that facilitates navigation and URL manipulation
* Injectable service provided at root level
*/
class Router {
/** Stream of router navigation events */
events: Observable<Event>;
/** Current state of routing as a tree */
routerState: RouterState;
/** True if at least one navigation event has occurred */
navigated: boolean;
/** Current route configuration array */
config: Routes;
/** Current URL as string */
url: string;
/** Signal of current navigation (readonly) */
currentNavigation: Signal<Navigation | null>;
/**
* Navigate based on commands array
* @param commands Array of URL segments and parameters
* @param extras Optional navigation configuration
* @returns Promise that resolves to true if navigation succeeds
*/
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
/**
* Navigate to absolute URL
* @param url Target URL as string or UrlTree
* @param extras Optional navigation behavior options
* @returns Promise that resolves to true if navigation succeeds
*/
navigateByUrl(url: string | UrlTree, extras?: NavigationBehaviorOptions): Promise<boolean>;
/**
* Create URL tree from commands without navigating
* @param commands Array of URL segments and parameters
* @param navigationExtras Optional URL creation options
* @returns UrlTree representation of the URL
*/
createUrlTree(commands: any[], navigationExtras?: UrlCreationOptions): UrlTree;
/**
* Serialize URL tree to string
* @param url UrlTree to serialize
* @returns String representation of the URL
*/
serializeUrl(url: UrlTree): string;
/**
* Parse string URL into URL tree
* @param url String URL to parse
* @returns UrlTree representation
*/
parseUrl(url: string): UrlTree;
/**
* Check if URL is currently active
* @param url URL to check as string or UrlTree
* @param matchOptions Options for matching logic
* @returns True if URL matches current route
*/
isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean;
/**
* Reset route configuration
* @param config New route configuration array
*/
resetConfig(config: Routes): void;
/**
* Set up initial navigation and location change listener
*/
initialNavigation(): void;
/**
* Set up location change listener for browser navigation
*/
setUpLocationChangeListener(): void;
/**
* Get current navigation object (deprecated - use currentNavigation signal)
* @deprecated Use currentNavigation signal instead
* @returns Current navigation or null if idle
*/
getCurrentNavigation(): Navigation | null;
/**
* Clean up router resources and subscriptions
*/
dispose(): void;
/** Strategy for re-using routes (deprecated) */
routeReuseStrategy: RouteReuseStrategy;
/** How to handle navigation to same URL (deprecated) */
onSameUrlNavigation: OnSameUrlNavigation;
/** Whether component input binding is enabled */
readonly componentInputBindingEnabled: boolean;
/** Last successful navigation */
readonly lastSuccessfulNavigation: Navigation | null;
}Usage Examples:
import { Router } from '@angular/router';
@Component({})
export class MyComponent {
constructor(private router: Router) {}
// Simple navigation
goHome() {
this.router.navigate(['/']);
}
// Navigation with parameters
viewUser(userId: number) {
this.router.navigate(['/users', userId]);
}
// Navigation with query parameters and fragment
searchUsers(query: string) {
this.router.navigate(['/users'], {
queryParams: { search: query, page: 1 },
fragment: 'results'
});
}
// Navigate by URL
goToUrl(url: string) {
this.router.navigateByUrl(url);
}
// Check if route is active
isUsersActive(): boolean {
return this.router.isActive('/users', { paths: 'subset', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' });
}
// Listen to navigation events
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
console.log('Navigation completed to:', event.url);
}
});
}
}Core navigation functionality for programmatic routing.
/**
* Navigate based on commands array
* @param commands Array of URL segments and parameters
* @param extras Optional navigation configuration
* @returns Promise that resolves to true if navigation succeeds
*/
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
/**
* Navigate to absolute URL
* @param url Target URL as string or UrlTree
* @param extras Optional navigation behavior options
* @returns Promise that resolves to true if navigation succeeds
*/
navigateByUrl(url: string | UrlTree, extras?: NavigationBehaviorOptions): Promise<boolean>;Navigation Commands Format:
// Simple paths
router.navigate(['/home']);
router.navigate(['/users', userId]);
router.navigate(['/users', userId, 'profile']);
// Matrix parameters
router.navigate(['/users', userId, { tab: 'profile', mode: 'edit' }]);
// Relative navigation
router.navigate(['../sibling'], { relativeTo: this.route });
router.navigate(['./child'], { relativeTo: this.route });
// Complex navigation with all options
router.navigate(['/users', userId], {
queryParams: { search: 'john', page: 2 },
fragment: 'details',
queryParamsHandling: 'merge',
preserveFragment: true,
skipLocationChange: false,
replaceUrl: false,
state: { from: 'search-results' }
});URL creation, parsing, and manipulation methods.
/**
* Create URL tree from commands without navigating
* @param commands Array of URL segments and parameters
* @param navigationExtras Optional URL creation options
* @returns UrlTree representation of the URL
*/
createUrlTree(commands: any[], navigationExtras?: UrlCreationOptions): UrlTree;
/**
* Serialize URL tree to string
* @param url UrlTree to serialize
* @returns String representation of the URL
*/
serializeUrl(url: UrlTree): string;
/**
* Parse string URL into URL tree
* @param url String URL to parse
* @returns UrlTree representation
*/
parseUrl(url: string): UrlTree;
/**
* Check if URL is currently active
* @param url URL to check as string or UrlTree
* @param matchOptions Options for matching logic
* @returns True if URL matches current route
*/
isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean;Access to current routing state and configuration.
/** Stream of router navigation events */
events: Observable<Event>;
/** Current state of routing as a tree */
routerState: RouterState;
/** True if at least one navigation event has occurred */
navigated: boolean;
/** Current route configuration array */
config: Routes;
/** Current URL as string */
url: string;
/** Signal of current navigation (readonly) */
currentNavigation: Signal<Navigation | null>;Accessing Router State:
import { Router, NavigationEnd } from '@angular/router';
@Component({})
export class AppComponent {
constructor(private router: Router) {
// Listen to all navigation events
this.router.events.subscribe(event => {
console.log('Router event:', event);
});
// Listen to specific events
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
console.log('Navigation ended:', event.url);
});
}
getCurrentUrl(): string {
return this.router.url;
}
hasNavigated(): boolean {
return this.router.navigated;
}
getCurrentRouteConfig(): Routes {
return this.router.config;
}
}Managing and updating route configuration at runtime.
/**
* Reset route configuration
* @param config New route configuration array
*/
resetConfig(config: Routes): void;
/** Current route configuration array */
config: Routes;Dynamic Route Configuration:
import { Router } from '@angular/router';
@Component({})
export class AdminComponent {
constructor(private router: Router) {}
// Add routes dynamically (be careful with this approach)
addAdminRoutes() {
const currentConfig = this.router.config;
const newRoutes = [
{ path: 'admin/dashboard', component: AdminDashboardComponent },
{ path: 'admin/users', component: AdminUsersComponent }
];
this.router.resetConfig([...currentConfig, ...newRoutes]);
}
}interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {}
interface UrlCreationOptions {
/** Route to use as base for relative navigation */
relativeTo?: ActivatedRoute | null;
/** Query parameters to add to URL */
queryParams?: Params | null;
/** URL fragment to add */
fragment?: string | null;
/** How to handle existing query parameters */
queryParamsHandling?: QueryParamsHandling | null;
/** Whether to preserve current fragment */
preserveFragment?: boolean;
}
interface NavigationBehaviorOptions {
/** How to handle navigation to same URL */
onSameUrlNavigation?: OnSameUrlNavigation;
/** Whether to skip updating browser location */
skipLocationChange?: boolean;
/** Whether to replace current URL in history */
replaceUrl?: boolean;
/** State to persist to browser history */
state?: {[k: string]: any};
/** Transient information about navigation */
info?: unknown;
/** Custom URL for browser location bar */
browserUrl?: string | UrlTree;
}
interface IsActiveMatchOptions {
/** How to match matrix parameters */
matrixParams: 'exact' | 'subset' | 'ignored';
/** How to match query parameters */
queryParams: 'exact' | 'subset' | 'ignored';
/** How to match URL paths */
paths: 'exact' | 'subset';
/** How to match URL fragment */
fragment: 'exact' | 'ignored';
}
interface Navigation {
/** Unique navigation ID */
id: number;
/** Initial URL for navigation */
initialUrl: UrlTree;
/** URL after redirects */
extractedUrl: UrlTree;
/** Final URL after all processing */
finalUrl?: UrlTree;
/** What triggered the navigation */
trigger: 'imperative' | 'popstate' | 'hashchange';
/** Navigation extras */
extras: NavigationExtras;
/** Previous navigation */
previousNavigation: Navigation | null;
/** Function to abort navigation */
abort(): void;
}
type OnSameUrlNavigation = 'reload' | 'ignore';
type QueryParamsHandling = 'merge' | 'preserve' | 'replace' | '';