UNPKG

@angular/router

Version:
1,417 lines (1,408 loc) 152 kB
/** * @license Angular v22.0.0 * (c) 2010-2026 Google LLC. https://angular.dev/ * License: MIT */ import * as i0 from '@angular/core'; import { InjectionToken, EnvironmentInjector, ComponentRef, EventEmitter, Signal, OnDestroy, OnInit, SimpleChanges, Type, DefaultExport, ProviderToken, NgModuleFactory, Provider, EnvironmentProviders, OnChanges, Renderer2, ElementRef, AfterContentInit, QueryList, ChangeDetectorRef, ModuleWithProviders } from '@angular/core'; import { Observable } from 'rxjs'; import { LocationStrategy } from '@angular/common'; /** * Identifies the call or event that triggered a navigation. * * * 'imperative': Triggered by `router.navigateByUrl()` or `router.navigate()`. * * 'popstate' : Triggered by a `popstate` event. * * 'hashchange'-: Triggered by a `hashchange` event. * * @publicApi */ type NavigationTrigger = 'imperative' | 'popstate' | 'hashchange'; /** * Identifies the type of a router event. * * @see [Router Lifecycle and Events](guide/routing/lifecycle-and-events) * * @publicApi */ declare enum EventType { NavigationStart = 0, NavigationEnd = 1, NavigationCancel = 2, NavigationError = 3, RoutesRecognized = 4, ResolveStart = 5, ResolveEnd = 6, GuardsCheckStart = 7, GuardsCheckEnd = 8, RouteConfigLoadStart = 9, RouteConfigLoadEnd = 10, ChildActivationStart = 11, ChildActivationEnd = 12, ActivationStart = 13, ActivationEnd = 14, Scroll = 15, NavigationSkipped = 16 } /** * Base for events the router goes through, as opposed to events tied to a specific * route. Fired one time for any given navigation. * * The following code shows how a class subscribes to router events. * * ```ts * import {Event, RouterEvent, Router} from '@angular/router'; * * class MyService { * constructor(public router: Router) { * router.events.pipe( * filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent) * ).subscribe((e: RouterEvent) => { * // Do something * }); * } * } * ``` * * @see {@link Event} * @see [Router events summary](guide/routing/router-reference#router-events) * @publicApi */ declare class RouterEvent { /** A unique ID that the router assigns to every router navigation. */ id: number; /** The URL that is the destination for this navigation. */ url: string; constructor( /** A unique ID that the router assigns to every router navigation. */ id: number, /** The URL that is the destination for this navigation. */ url: string); } /** * An event triggered when a navigation starts. * * @publicApi */ declare class NavigationStart extends RouterEvent { readonly type = EventType.NavigationStart; /** * Identifies the call or event that triggered the navigation. * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`. * * @see {@link NavigationEnd} * @see {@link NavigationCancel} * @see {@link NavigationError} */ navigationTrigger?: NavigationTrigger; /** * The navigation state that was previously supplied to the `pushState` call, * when the navigation is triggered by a `popstate` event. Otherwise null. * * The state object is defined by `NavigationExtras`, and contains any * developer-defined state value, as well as a unique ID that * the router assigns to every router transition/navigation. * * From the perspective of the router, the router never "goes back". * When the user clicks on the back button in the browser, * a new navigation ID is created. * * Use the ID in this previous-state object to differentiate between a newly created * state and one returned to by a `popstate` event, so that you can restore some * remembered state, such as scroll position. * */ restoredState?: { [k: string]: any; navigationId: number; } | null; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ navigationTrigger?: NavigationTrigger, /** @docsNotRequired */ restoredState?: { [k: string]: any; navigationId: number; } | null); /** @docs-private */ toString(): string; } /** * An event triggered when a navigation ends successfully. * * @see {@link NavigationStart} * @see {@link NavigationCancel} * @see {@link NavigationError} * * @publicApi */ declare class NavigationEnd extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; readonly type = EventType.NavigationEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string); /** @docs-private */ toString(): string; } /** * A code for the `NavigationCancel` event of the `Router` to indicate the * reason a navigation failed. * * @publicApi */ declare enum NavigationCancellationCode { /** * A navigation failed because a guard returned a `UrlTree` to redirect. */ Redirect = 0, /** * A navigation failed because a more recent navigation started. */ SupersededByNewNavigation = 1, /** * A navigation failed because one of the resolvers completed without emitting a value. */ NoDataFromResolver = 2, /** * A navigation failed because a guard returned `false`. */ GuardRejected = 3, /** * A navigation was aborted by the `Navigation.abort` function. * * @see {@link Navigation} */ Aborted = 4 } /** * A code for the `NavigationSkipped` event of the `Router` to indicate the * reason a navigation was skipped. * * @publicApi */ declare enum NavigationSkippedCode { /** * A navigation was skipped because the navigation URL was the same as the current Router URL. */ IgnoredSameUrlNavigation = 0, /** * A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both * the current Router URL and the target of the navigation. * * @see {@link UrlHandlingStrategy} */ IgnoredByUrlHandlingStrategy = 1 } /** * An event triggered when a navigation is canceled, directly or indirectly. * This can happen for several reasons including when a route guard * returns `false` or initiates a redirect by returning a `UrlTree`. * * @see {@link NavigationStart} * @see {@link NavigationEnd} * @see {@link NavigationError} * * @publicApi */ declare class NavigationCancel extends RouterEvent { /** * A description of why the navigation was cancelled. For debug purposes only. Use `code` * instead for a stable cancellation reason that can be used in production. */ reason: string; /** * A code to indicate why the navigation was canceled. This cancellation code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ readonly code?: NavigationCancellationCode | undefined; readonly type = EventType.NavigationCancel; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** * A description of why the navigation was cancelled. For debug purposes only. Use `code` * instead for a stable cancellation reason that can be used in production. */ reason: string, /** * A code to indicate why the navigation was canceled. This cancellation code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ code?: NavigationCancellationCode | undefined); /** @docs-private */ toString(): string; } /** * An event triggered when a navigation is skipped. * This can happen for a couple reasons including onSameUrlHandling * is set to `ignore` and the navigation URL is not different than the * current state. * * @publicApi */ declare class NavigationSkipped extends RouterEvent { /** * A description of why the navigation was skipped. For debug purposes only. Use `code` * instead for a stable skipped reason that can be used in production. */ reason: string; /** * A code to indicate why the navigation was skipped. This code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ readonly code?: NavigationSkippedCode | undefined; readonly type = EventType.NavigationSkipped; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** * A description of why the navigation was skipped. For debug purposes only. Use `code` * instead for a stable skipped reason that can be used in production. */ reason: string, /** * A code to indicate why the navigation was skipped. This code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ code?: NavigationSkippedCode | undefined); } /** * An event triggered when a navigation fails due to an unexpected error. * * @see {@link NavigationStart} * @see {@link NavigationEnd} * @see {@link NavigationCancel} * * @publicApi */ declare class NavigationError extends RouterEvent { /** @docsNotRequired */ error: any; /** * The target of the navigation when the error occurred. * * Note that this can be `undefined` because an error could have occurred before the * `RouterStateSnapshot` was created for the navigation. */ readonly target?: RouterStateSnapshot | undefined; readonly type = EventType.NavigationError; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ error: any, /** * The target of the navigation when the error occurred. * * Note that this can be `undefined` because an error could have occurred before the * `RouterStateSnapshot` was created for the navigation. */ target?: RouterStateSnapshot | undefined); /** @docs-private */ toString(): string; } /** * An event triggered when routes are recognized. * * @publicApi */ declare class RoutesRecognized extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; /** @docsNotRequired */ state: RouterStateSnapshot; readonly type = EventType.RoutesRecognized; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string, /** @docsNotRequired */ state: RouterStateSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the start of the Guard phase of routing. * * @see {@link GuardsCheckEnd} * * @publicApi */ declare class GuardsCheckStart extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; /** @docsNotRequired */ state: RouterStateSnapshot; readonly type = EventType.GuardsCheckStart; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string, /** @docsNotRequired */ state: RouterStateSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the end of the Guard phase of routing. * * @see {@link GuardsCheckStart} * * @publicApi */ declare class GuardsCheckEnd extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; /** @docsNotRequired */ state: RouterStateSnapshot; /** @docsNotRequired */ shouldActivate: boolean; readonly type = EventType.GuardsCheckEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string, /** @docsNotRequired */ state: RouterStateSnapshot, /** @docsNotRequired */ shouldActivate: boolean); /** @docs-private */ toString(): string; } /** * An event triggered at the start of the Resolve phase of routing. * * Runs in the "resolve" phase whether or not there is anything to resolve. * In future, may change to only run when there are things to be resolved. * * @see {@link ResolveEnd} * * @publicApi */ declare class ResolveStart extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; /** @docsNotRequired */ state: RouterStateSnapshot; readonly type = EventType.ResolveStart; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string, /** @docsNotRequired */ state: RouterStateSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the end of the Resolve phase of routing. * @see {@link ResolveStart} * * @publicApi */ declare class ResolveEnd extends RouterEvent { /** @docsNotRequired */ urlAfterRedirects: string; /** @docsNotRequired */ state: RouterStateSnapshot; readonly type = EventType.ResolveEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ urlAfterRedirects: string, /** @docsNotRequired */ state: RouterStateSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered before lazy loading a route configuration. * * @see {@link RouteConfigLoadEnd} * * @publicApi */ declare class RouteConfigLoadStart { /** @docsNotRequired */ route: Route; readonly type = EventType.RouteConfigLoadStart; constructor( /** @docsNotRequired */ route: Route); /** @docs-private */ toString(): string; } /** * An event triggered when a route has been lazy loaded. * * @see {@link RouteConfigLoadStart} * * @publicApi */ declare class RouteConfigLoadEnd { /** @docsNotRequired */ route: Route; readonly type = EventType.RouteConfigLoadEnd; constructor( /** @docsNotRequired */ route: Route); /** @docs-private */ toString(): string; } /** * An event triggered at the start of the child-activation * part of the Resolve phase of routing. * @see {@link ChildActivationEnd} * @see {@link ResolveStart} * * @publicApi */ declare class ChildActivationStart { /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot; readonly type = EventType.ChildActivationStart; constructor( /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the end of the child-activation part * of the Resolve phase of routing. * @see {@link ChildActivationStart} * @see {@link ResolveStart} * @publicApi */ declare class ChildActivationEnd { /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot; readonly type = EventType.ChildActivationEnd; constructor( /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the start of the activation part * of the Resolve phase of routing. * @see {@link ActivationEnd} * @see {@link ResolveStart} * * @publicApi */ declare class ActivationStart { /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot; readonly type = EventType.ActivationStart; constructor( /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered at the end of the activation part * of the Resolve phase of routing. * @see {@link ActivationStart} * @see {@link ResolveStart} * * @publicApi */ declare class ActivationEnd { /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot; readonly type = EventType.ActivationEnd; constructor( /** @docsNotRequired */ snapshot: ActivatedRouteSnapshot); /** @docs-private */ toString(): string; } /** * An event triggered by scrolling. * * @publicApi */ declare class Scroll { /** @docsNotRequired */ readonly routerEvent: NavigationEnd | NavigationSkipped; /** @docsNotRequired */ readonly position: [number, number] | null; /** @docsNotRequired */ readonly anchor: string | null; /** @docsNotRequired */ readonly scrollBehavior?: "manual" | "after-transition" | undefined; readonly type = EventType.Scroll; constructor( /** @docsNotRequired */ routerEvent: NavigationEnd | NavigationSkipped, /** @docsNotRequired */ position: [number, number] | null, /** @docsNotRequired */ anchor: string | null, /** @docsNotRequired */ scrollBehavior?: "manual" | "after-transition" | undefined); /** @docs-private */ toString(): string; } /** * Router events that allow you to track the lifecycle of the router. * * The events occur in the following sequence: * * * [NavigationStart](api/router/NavigationStart): Navigation starts. * * [RouteConfigLoadStart](api/router/RouteConfigLoadStart): Before * the router [lazy loads](guide/routing/common-router-tasks#lazy-loading) a route configuration. * * [RouteConfigLoadEnd](api/router/RouteConfigLoadEnd): After a route has been lazy loaded. * * [RoutesRecognized](api/router/RoutesRecognized): When the router parses the URL * and the routes are recognized. * * [GuardsCheckStart](api/router/GuardsCheckStart): When the router begins the *guards* * phase of routing. * * [ChildActivationStart](api/router/ChildActivationStart): When the router * begins activating a route's children. * * [ActivationStart](api/router/ActivationStart): When the router begins activating a route. * * [GuardsCheckEnd](api/router/GuardsCheckEnd): When the router finishes the *guards* * phase of routing successfully. * * [ResolveStart](api/router/ResolveStart): When the router begins the *resolve* * phase of routing. * * [ResolveEnd](api/router/ResolveEnd): When the router finishes the *resolve* * phase of routing successfully. * * [ChildActivationEnd](api/router/ChildActivationEnd): When the router finishes * activating a route's children. * * [ActivationEnd](api/router/ActivationEnd): When the router finishes activating a route. * * [NavigationEnd](api/router/NavigationEnd): When navigation ends successfully. * * [NavigationCancel](api/router/NavigationCancel): When navigation is canceled. * * [NavigationError](api/router/NavigationError): When navigation fails * due to an unexpected error. * * [Scroll](api/router/Scroll): When the user scrolls. * * @publicApi */ type Event = NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized | GuardsCheckStart | GuardsCheckEnd | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd | Scroll | ResolveStart | ResolveEnd | NavigationSkipped; /** * The primary routing outlet. * * @publicApi */ declare const PRIMARY_OUTLET = "primary"; /** * A collection of matrix and query URL parameters. * @see {@link convertToParamMap} * @see {@link ParamMap} * * @publicApi */ type Params = { [key: string]: any; }; /** * A map that provides access to the required and optional parameters * specific to a route. * The map supports retrieving a single value with `get()` * or multiple values with `getAll()`. * * @see [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) * * @publicApi */ interface ParamMap { /** * Reports whether the map contains a given parameter. * @param name The parameter name. * @returns True if the map contains the given parameter, false otherwise. */ has(name: string): boolean; /** * Retrieves a single value for a parameter. * @param name The parameter name. * @return The parameter's single value, * or the first value if the parameter has multiple values, * or `null` when there is no such parameter. */ get(name: string): string | null; /** * Retrieves multiple values for a parameter. * @param name The parameter name. * @return An array containing one or more values, * or an empty array if there is no such parameter. * */ getAll(name: string): string[]; /** Names of the parameters in the map. */ readonly keys: string[]; } /** * Converts a `Params` instance to a `ParamMap`. * @param params The instance to convert. * @returns The new map instance. * * @publicApi */ declare function convertToParamMap(params: Params): ParamMap; /** * Matches the route configuration (`route`) against the actual URL (`segments`). * * When no matcher is defined on a `Route`, this is the matcher used by the Router by default. * * @param segments The remaining unmatched segments in the current navigation * @param segmentGroup The current segment group being matched * @param route The `Route` to match against. * * @see {@link UrlMatchResult} * @see {@link Route} * * @returns The resulting match information or `null` if the `route` should not match. * @publicApi */ declare function defaultUrlMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null; /** * Allowed values in an `ExtraOptions` object that configure * when the router performs the initial navigation operation. * * * 'enabledNonBlocking' - (default) The initial navigation starts after the * root component has been created. The bootstrap is not blocked on the completion of the initial * navigation. * * 'enabledBlocking' - The initial navigation starts before the root component is created. * The bootstrap is blocked until the initial navigation is complete. This value should be set in * case you use [server-side rendering](guide/ssr), but do not enable [hydration](guide/hydration) * for your application. * * 'disabled' - The initial navigation is not performed. The location listener is set up before * the root component gets created. Use if there is a reason to have * more control over when the router starts its initial navigation due to some complex * initialization logic. * * @see {@link /api/router/RouterModule#forRoot forRoot} * * @publicApi */ type InitialNavigation = 'disabled' | 'enabledBlocking' | 'enabledNonBlocking'; /** * Extra configuration options that can be used with the `withRouterConfig` function. * * @see [Router configuration options](guide/routing/customizing-route-behavior#router-configuration-options) * * @publicApi */ interface RouterConfigOptions { /** * Configures how the Router attempts to restore state when a navigation is cancelled. * * 'replace' - Always uses `location.replaceState` to set the browser state to the state of the * router before the navigation started. This means that if the URL of the browser is updated * _before_ the navigation is canceled, the Router will simply replace the item in history rather * than trying to restore to the previous location in the session history. This happens most * frequently with `urlUpdateStrategy: 'eager'` and navigations with the browser back/forward * buttons. * * 'computed' - Will attempt to return to the same index in the session history that corresponds * to the Angular route when the navigation gets cancelled. For example, if the browser back * button is clicked and the navigation is cancelled, the Router will trigger a forward navigation * and vice versa. * * Note: the 'computed' option is incompatible with any `UrlHandlingStrategy` which only * handles a portion of the URL because the history restoration navigates to the previous place in * the browser history rather than simply resetting a portion of the URL. * * The default value is `replace` when not set. * * @see [Handle canceled navigations](guide/routing/customizing-route-behavior#handle-canceled-navigations) * */ canceledNavigationResolution?: 'replace' | 'computed'; /** * Configures the default for handling a navigation request to the current URL. * * If unset, the `Router` will use `'ignore'`. * * @see {@link OnSameUrlNavigation} * * @see [React to same-URL navigations](guide/routing/customizing-route-behavior#react-to-same-url-navigations) */ onSameUrlNavigation?: OnSameUrlNavigation; /** * Defines how the router merges parameters, data, and resolved data from parent to child * routes. * * By default ('always'), a route inherits all parameters from its parent routes. * * Set to 'emptyOnly' to preserve the legacy behavior where a route only inherits the parent * route's parameters when the route itself has an empty path or when the parent route doesn't * have any component set. * * Note that when dealing with matrix parameters, "parent" refers to the parent `Route` * config which does not necessarily mean the "URL segment to the left". When the `Route` `path` * contains multiple segments, the matrix parameters must appear on the last segment. For example, * matrix parameters for `{path: 'a/b', component: MyComp}` should appear as `a/b;foo=bar` and not * `a;foo=bar/b`. * * @see [Control parameter inheritance](guide/routing/customizing-route-behavior#control-parameter-inheritance) * */ paramsInheritanceStrategy?: 'emptyOnly' | 'always'; /** * Defines when the router updates the browser URL. By default ('deferred'), * update after successful navigation. * Set to 'eager' if prefer to update the URL at the beginning of navigation. * Updating the URL early allows you to handle a failure of navigation by * showing an error message with the URL that failed. * * @see [Decide when the URL updates](guide/routing/customizing-route-behavior#decide-when-the-url-updates) * */ urlUpdateStrategy?: 'deferred' | 'eager'; /** * The default strategy to use for handling query params in `Router.createUrlTree` when one is not provided. * * The `createUrlTree` method is used internally by `Router.navigate` and `RouterLink`. * Note that `QueryParamsHandling` does not apply to `Router.navigateByUrl`. * * When neither the default nor the queryParamsHandling option is specified in the call to `createUrlTree`, * the current parameters will be replaced by new parameters. * * @see {@link Router#createUrlTree} * @see {@link QueryParamsHandling} * * @see [Choose default query parameter handling](guide/routing/customizing-route-behavior#choose-default-query-parameter-handling) * */ defaultQueryParamsHandling?: QueryParamsHandling; /** * When `true`, the `Promise` will instead resolve with `false`, as it does with other failed * navigations (for example, when guards are rejected). * Otherwise the `Promise` returned by the Router's navigation with be rejected * if an error occurs. */ resolveNavigationPromiseOnError?: boolean; } /** * Configuration options for the scrolling feature which can be used with `withInMemoryScrolling` * function or `RouterModule.forRoot`. * * @publicApi * @see withInMemoryScrolling * @see RouterModule#forRoot */ interface InMemoryScrollingOptions { /** * When set to 'enabled', scrolls to the anchor element when the URL has a fragment. * Anchor scrolling is disabled by default. * * Anchor scrolling does not happen on 'popstate'. Instead, we restore the position * that we stored or scroll to the top. */ anchorScrolling?: 'disabled' | 'enabled'; /** * Configures if the scroll position needs to be restored when navigating back. * * * 'disabled'- (Default) Does nothing. Scroll position is maintained on navigation. * * 'top'- Sets the scroll position to x = 0, y = 0 on all navigation. * * 'enabled'- Restores the previous scroll position on backward navigation, else sets the * position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward * navigation). This option will be the default in the future. * * You can implement custom scroll restoration behavior by adapting the enabled behavior as * in the following example. * * ```ts * class AppComponent { * movieData: any; * * constructor(private router: Router, private viewportScroller: ViewportScroller, * changeDetectorRef: ChangeDetectorRef) { * router.events.pipe(filter((event: Event): event is Scroll => event instanceof Scroll) * ).subscribe(e => { * fetch('http://example.com/movies.json').then(response => { * this.movieData = response.json(); * // update the template with the data before restoring scroll * changeDetectorRef.detectChanges(); * * if (e.position) { * viewportScroller.scrollToPosition(e.position); * } * }); * }); * } * } * ``` */ scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'; } /** * Configuration options for the component input binding feature which can be used * with `withComponentInputBinding` function or `RouterModule.forRoot` * * @publicApi * @see withComponentInputBinding * @see RouterModule#forRoot * @see [Disable query parameter binding](guide/routing/common-router-tasks#disable-query-parameter-binding) */ interface ComponentInputBindingOptions { /** * When true (default), will configure query parameters to bind to component * inputs. */ queryParams?: boolean; /** * Configures the behavior when an input is not matched by any key in the router data. * * - `'alwaysUndefined'`: (Default) Binds `undefined` to the input. This ensures that stale data * is not retained. * - `'undefinedIfStale'`: Binds `undefined` only if the input was previously available * in the router data during the lifetime of the active route in this outlet. This avoids * setting `undefined` for inputs that were never expected to be set by the router. */ unmatchedInputBehavior?: 'alwaysUndefined' | 'undefinedIfStale'; } /** * A set of configuration options for a router module, provided in the * `forRoot()` method. * * @see {@link /api/router/RouterModule#forRoot forRoot} * * * @publicApi */ interface ExtraOptions extends InMemoryScrollingOptions, RouterConfigOptions { /** * When true, log all internal navigation events to the console. * Use for debugging. */ enableTracing?: boolean; /** * When true, enable the location strategy that uses the URL fragment * instead of the history API. */ useHash?: boolean; /** * One of `enabled`, `enabledBlocking`, `enabledNonBlocking` or `disabled`. * When set to `enabled` or `enabledBlocking`, the initial navigation starts before the root * component is created. The bootstrap is blocked until the initial navigation is complete. This * value should be set in case you use [server-side rendering](guide/ssr), but do not enable * [hydration](guide/hydration) for your application. When set to `enabledNonBlocking`, * the initial navigation starts after the root component has been created. * The bootstrap is not blocked on the completion of the initial navigation. When set to * `disabled`, the initial navigation is not performed. The location listener is set up before the * root component gets created. Use if there is a reason to have more control over when the router * starts its initial navigation due to some complex initialization logic. */ initialNavigation?: InitialNavigation; /** * When true, enables binding information from the `Router` state directly to the inputs of the * component in `Route` configurations. Can also accept an `ComponentInputBindingOptions` object * to set whether to exclude queryParams from binding. */ bindToComponentInputs?: boolean | ComponentInputBindingOptions; /** * When true, enables view transitions in the Router by running the route activation and * deactivation inside of `document.startViewTransition`. * * @see https://developer.chrome.com/docs/web-platform/view-transitions/ * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API * @experimental 17.0 */ enableViewTransitions?: boolean; /** * A custom error handler for failed navigations. * If the handler returns a value, the navigation Promise is resolved with this value. * If the handler throws an exception, the navigation Promise is rejected with the exception. * * @see RouterConfigOptions */ errorHandler?: (error: any) => RedirectCommand | any; /** * Configures a preloading strategy. * One of `PreloadAllModules` or `NoPreloading` (the default). */ preloadingStrategy?: any; /** * Configures the scroll offset the router will use when scrolling to an element. * * When given a tuple with x and y position value, * the router uses that offset each time it scrolls. * When given a function, the router invokes the function every time * it restores scroll position. */ scrollOffset?: [number, number] | (() => [number, number]); } /** * A DI token for the router service. * * @publicApi */ declare const ROUTER_CONFIGURATION: InjectionToken<ExtraOptions>; /** * An `InjectionToken` provided by the `RouterOutlet` and can be set using the `routerOutletData` * input. * * When unset, this value is `null` by default. * * @usageNotes * * To set the data from the template of the component with `router-outlet`: * ```html * <router-outlet [routerOutletData]="{name: 'Angular'}" /> * ``` * * To read the data in the routed component: * ```ts * data = inject(ROUTER_OUTLET_DATA) as Signal<{name: string}>; * ``` * * @publicApi * @see [Page routerOutletData](guide/routing/show-routes-with-outlets#passing-contextual-data-to-routed-components) */ declare const ROUTER_OUTLET_DATA: InjectionToken<Signal<unknown>>; /** * An interface that defines the contract for developing a component outlet for the `Router`. * * An outlet acts as a placeholder that Angular dynamically fills based on the current router state. * * A router outlet should register itself with the `Router` via * `ChildrenOutletContexts#onChildOutletCreated` and unregister with * `ChildrenOutletContexts#onChildOutletDestroyed`. When the `Router` identifies a matched `Route`, * it looks for a registered outlet in the `ChildrenOutletContexts` and activates it. * * @see {@link ChildrenOutletContexts} * @publicApi */ interface RouterOutletContract { /** * Whether the given outlet is activated. * * An outlet is considered "activated" if it has an active component. */ isActivated: boolean; /** The instance of the activated component or `null` if the outlet is not activated. */ component: Object | null; /** * The `Data` of the `ActivatedRoute` snapshot. */ activatedRouteData: Data; /** * The `ActivatedRoute` for the outlet or `null` if the outlet is not activated. */ activatedRoute: ActivatedRoute | null; /** * Called by the `Router` when the outlet should activate (create a component). */ activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector): void; /** * A request to destroy the currently activated component. * * When a `RouteReuseStrategy` indicates that an `ActivatedRoute` should be removed but stored for * later re-use rather than destroyed, the `Router` will call `detach` instead. */ deactivate(): void; /** * Called when the `RouteReuseStrategy` instructs to detach the subtree. * * This is similar to `deactivate`, but the activated component should _not_ be destroyed. * Instead, it is returned so that it can be reattached later via the `attach` method. */ detach(): ComponentRef<unknown>; /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree. */ attach(ref: ComponentRef<unknown>, activatedRoute: ActivatedRoute): void; /** * Emits an activate event when a new component is instantiated **/ activateEvents?: EventEmitter<unknown>; /** * Emits a deactivate event when a component is destroyed. */ deactivateEvents?: EventEmitter<unknown>; /** * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a * previously detached subtree. **/ attachEvents?: EventEmitter<unknown>; /** * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the * subtree. */ detachEvents?: EventEmitter<unknown>; /** * Used to indicate that the outlet is able to bind data from the `Router` to the outlet * component's inputs. * * When this is `undefined` or `false` and the developer has opted in to the * feature using `withComponentInputBinding`, a warning will be logged in dev mode if this outlet * is used in the application. */ readonly supportsBindingToComponentInputs?: true; } /** * @description * * Acts as a placeholder that Angular dynamically fills based on the current router state. * * Each outlet can have a unique name, determined by the optional `name` attribute. * The name cannot be set or changed dynamically. If not set, default value is "primary". * * ```html * <router-outlet></router-outlet> * <router-outlet name='left'></router-outlet> * <router-outlet name='right'></router-outlet> * ``` * * Named outlets can be the targets of secondary routes. * The `Route` object for a secondary route has an `outlet` property to identify the target outlet: * * `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}` * * Using named outlets and secondary routes, you can target multiple outlets in * the same `RouterLink` directive. * * The router keeps track of separate branches in a navigation tree for each named outlet and * generates a representation of that tree in the URL. * The URL for a secondary route uses the following syntax to specify both the primary and secondary * routes at the same time: * * `http://base-path/primary-route-path(outlet-name:route-path)` * * A router outlet emits an activate event when a new component is instantiated, * deactivate event when a component is destroyed. * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to * detach the subtree. * * ```html * <router-outlet * (activate)='onActivate($event)' * (deactivate)='onDeactivate($event)' * (attach)='onAttach($event)' * (detach)='onDetach($event)'></router-outlet> * ``` * * @see {@link RouterLink} * @see {@link Route} * @see [Show routes with outlets](guide/routing/show-routes-with-outlets) * @ngModule RouterModule * * @publicApi */ declare class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract { private activated; private _activatedRoute; /** * The name of the outlet * */ name: string; activateEvents: EventEmitter<any>; deactivateEvents: EventEmitter<any>; /** * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a * previously detached subtree. **/ attachEvents: EventEmitter<unknown>; /** * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the * subtree. */ detachEvents: EventEmitter<unknown>; /** * Data that will be provided to the child injector through the `ROUTER_OUTLET_DATA` token. * * When unset, the value of the token is `undefined` by default. */ readonly routerOutletData: i0.InputSignal<unknown>; private parentContexts; private location; private changeDetector; private inputBinder; /** @docs-private */ readonly supportsBindingToComponentInputs = true; /** @docs-private */ ngOnChanges(changes: SimpleChanges): void; /** @docs-private */ ngOnDestroy(): void; private isTrackedInParentContexts; /** @docs-private */ ngOnInit(): void; private initializeOutletWithName; get isActivated(): boolean; /** * @returns The currently activated component instance. * @throws An error if the outlet is not activated. */ get component(): Object; get activatedRoute(): ActivatedRoute; get activatedRouteData(): Data; /** * Called when the `RouteReuseStrategy` instructs to detach the subtree */ detach(): ComponentRef<any>; /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree */ attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute): void; deactivate(): void; activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector): void; static ɵfac: i0.ɵɵFactoryDeclaration<RouterOutlet, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<RouterOutlet, "router-outlet", ["outlet"], { "name": { "alias": "name"; "required": false; }; "routerOutletData": { "alias": "routerOutletData"; "required": false; "isSignal": true; }; }, { "activateEvents": "activate"; "deactivateEvents": "deactivate"; "attachEvents": "attach"; "detachEvents": "detach"; }, never, never, true, never>; } /** * @description * * Options that modify the `Router` URL. * Supply an object containing any of these properties to a `Router` navigation function to * control how the target URL should be constructed. * * @see {@link Router#navigate} * @see {@link Router#createUrlTree} * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * * @publicApi */ interface UrlCreationOptions { /** * Specifies a root URI to use for relative navigation. * * For example, consider the following route configuration where the parent route * has two children. * * ```ts * [{ * path: 'parent', * component: ParentComponent, * children: [{ * path: 'list', * component: ListComponent * },{ * path: 'child', * component: ChildComponent * }] * }] * ``` * * The following `go()` function navigates to the `list` route by * interpreting the destination URI as relative to the activated `child` route * * ```ts * @Component({...}) * class ChildComponent { * constructor(private router: Router, private route: ActivatedRoute) {} * * go() { * router.navigate(['../list'], { relativeTo: this.route }); * } * } * ``` * * A value of `null` or `undefined` indicates that the navigation commands should be applied * relative to the root. */ relativeTo?: ActivatedRoute | null; /** * Sets query parameters to the URL. * * ```ts * // Navigate to /results?page=1 * router.navigate(['/results'], { queryParams: { page: 1 } }); * ``` */ queryParams?: Params | null; /** * Sets the hash fragment for the URL. * * ```ts * // Navigate to /results#top * router.navigate(['/results'], { fragment: 'top' }); * ``` */ fragment?: string; /** * How to handle query parameters in the router link for the next navigation. * One of: * * `preserve` : Preserve current parameters. * * `merge` : Merge new with current parameters. * * The "preserve" option discards any new query params: * ```ts * // from /view1?page=1 to/view2?page=1 * router.navigate(['/view2'], { queryParams: { page: 2 }, queryParamsHandling: "preserve" * }); * ``` * The "merge" option appends new query params to the params from the current URL: * ```ts * // from /view1?page=1 to/view2?page=1&otherKey=2 * router.navigate(['/view2'], { queryParams: { otherKey: 2 }, queryParamsHandling: "merge" * }); * ``` * In case of a key collision between current parameters and those in the `queryParams` object, * the new value is used. * */ queryParamsHandling?: QueryParamsHandling | null; /** * When true, preserves the URL fragment for the next navigation * * ```ts * // Preserve fragment from /results#top to /view#top * router.navigate(['/view'], { preserveFragment: true }); * ``` */ preserveFragment?: boolean; } /** * @description * * Options that modify the `Router` navigation strategy. * Supply an object containing any of these properties to a `Router` navigation function to * control how the target URL should be constructed or interpreted. * * @see {@link Router#navigate} * @see {@link Router#navigateByUrl} * @see {@link Router#createurltree} * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * @see {@link UrlCreationOptions} * @see {@link NavigationBehaviorOptions} * * @publicApi */ interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions { } type RestoredState = { [k: string]: any; navigationId: number; ɵrouterPageId?: number; ɵrouterUrl?: string; }; /** * Information about a navigation operation. * Retrieve the most recent navigation object with the * [Router.currentNavigation() method](api/router/Router#currentNavigation) . * * * *id* : The unique identifier of the current navigation. * * *initialUrl* : The target URL passed into the `Router#navigateByUrl()` call before navigation. * This is the value before the router has parsed or applied redirects to it. * * *extractedUrl* : The initial target URL after being parsed with `UrlSerializer.extract()`. * * *finalUrl* : The extracted URL after redirects have been applied. * This URL may not be available immediately, therefore this property can be `undefined`. * It is guaranteed to be set after the `RoutesRecognized` event fires. * * *trigger* : Identifies how this navigation was triggered. * -- 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`. * -- 'popstate'--Triggered by a popstate event. * -- 'hashchange'--Triggered by a hashchange event. * * *extras* : A `NavigationExtras` options object that controlled the strategy used for this * navigation. * * *previousNavigation* : The previously successful `Navigation` object. Only one previous * navigation is available, therefore this previous `Navigation` object has a `null` value for its * own `previousNavigation`. * * @publicApi */ interface Navigation { /** * The unique identifier of the current navigation. */ id: number; /** * The target URL passed into the `Router#navigateByUrl()` call before navigation. This is * the value before the router has parsed or applied redirects to it. */ initialUrl: UrlTree; /** * The initial target URL after being parsed with `UrlHandlingStrategy.extract()`. */ extractedUrl: UrlTree; /** * The extracted URL after redirects have been applied. * This URL may not be available immediately, therefore this property can be `undefined`. * It is guaranteed to be set after the `RoutesRecognized` event fires. */ finalUrl?: UrlTree; /** * Identifies how this navigation was triggered. */ trigger: NavigationTrigger; /** * Options that controlled the strategy used for this navigation. * See `NavigationExtras`. */ extras: NavigationExtras; /** * The previously successful `Navigation` object. Only one previous navigation * is available, therefore this previous `Navigation` object has a `null` value * for its own `previousNavigation`. */ previousNavigation: Navigation | null; /** * Aborts the navigation if it has not yet been completed or reached the point where routes are being activated. * This function is a no-op if the navigation is beyond the point where it can be aborted. */ readonly abort: () => void; } /** * @description * * Represents the detached route tree. * * This is an opaque value the router will give to a custom route reuse strategy * to store and retrieve later on. * * @publicApi */ type DetachedRouteHandle = {}; /** * @description * * Destroys the component associated with a `DetachedRouteHandle`. * * This function should be used when a `RouteReuseStrategy` decides to drop a stored handle * and wants to ensure that the component is destroyed. * * @param handle The detached route handle to destroy. * * @publicApi * @see [Manually destroying detached route handles](guide/routing/customizing-route-behavior#manually-destroying-detached-route-handles) */ declare function destroyDetachedRouteHandle(handle: DetachedRouteHandle): void; /** * @description * * Provides a way to customize when activated routes get reused. * * @publicApi */ declare abstract class RouteReuseStrategy { /** Determines if this route (and its subtree) should be detached to be reused later */ abstract sho