@angular/router
Version:
Angular - the routing library
1,489 lines (1,445 loc) • 115 kB
TypeScript
/**
* @license Angular v11.0.9
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
import { AfterContentInit } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { Compiler } from '@angular/core';
import { ComponentFactoryResolver } from '@angular/core';
import { ComponentRef } from '@angular/core';
import { ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { HashLocationStrategy } from '@angular/common';
import { InjectionToken } from '@angular/core';
import { Injector } from '@angular/core';
import { Location } from '@angular/common';
import { LocationStrategy } from '@angular/common';
import { ModuleWithProviders } from '@angular/core';
import { NgModuleFactory } from '@angular/core';
import { NgModuleFactoryLoader } from '@angular/core';
import { NgProbeToken } from '@angular/core';
import { Observable } from 'rxjs';
import { OnChanges } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { OnInit } from '@angular/core';
import { PathLocationStrategy } from '@angular/common';
import { PlatformLocation } from '@angular/common';
import { Provider } from '@angular/core';
import { QueryList } from '@angular/core';
import { Renderer2 } from '@angular/core';
import { SimpleChanges } from '@angular/core';
import { Type } from '@angular/core';
import { Version } from '@angular/core';
import { ViewContainerRef } from '@angular/core';
import { ViewportScroller } from '@angular/common';
/**
* Provides access to information about a route associated with a component
* that is loaded in an outlet.
* Use to traverse the `RouterState` tree and extract information from nodes.
*
* The following example shows how to construct a component using information from a
* currently activated route.
*
* {@example router/activated-route/module.ts region="activated-route"
* header="activated-route.component.ts"}
*
* @see [Getting route information](guide/router#getting-route-information)
*
* @publicApi
*/
export declare class ActivatedRoute {
/** An observable of the URL segments matched by this route. */
url: Observable<UrlSegment[]>;
/** An observable of the matrix parameters scoped to this route. */
params: Observable<Params>;
/** An observable of the query parameters shared by all the routes. */
queryParams: Observable<Params>;
/** An observable of the URL fragment shared by all the routes. */
fragment: Observable<string>;
/** An observable of the static and resolved data of this route. */
data: Observable<Data>;
/** The outlet name of the route, a constant. */
outlet: string;
/** The component of the route, a constant. */
component: Type<any> | string | null;
/** The current snapshot of this route */
snapshot: ActivatedRouteSnapshot;
/** The configuration used to match this route. */
get routeConfig(): Route | null;
/** The root of the router state. */
get root(): ActivatedRoute;
/** The parent of this route in the router state tree. */
get parent(): ActivatedRoute | null;
/** The first child of this route in the router state tree. */
get firstChild(): ActivatedRoute | null;
/** The children of this route in the router state tree. */
get children(): ActivatedRoute[];
/** The path from the root of the router state tree to this route. */
get pathFromRoot(): ActivatedRoute[];
/**
* An Observable that contains a map of the required and optional parameters
* specific to the route.
* The map supports retrieving single and multiple values from the same parameter.
*/
get paramMap(): Observable<ParamMap>;
/**
* An Observable that contains a map of the query parameters available to all routes.
* The map supports retrieving single and multiple values from the query parameter.
*/
get queryParamMap(): Observable<ParamMap>;
toString(): string;
}
/**
* @description
*
* Contains the information about a route associated with a component loaded in an
* outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
* traverse the router state tree.
*
* The following example initializes a component with route information extracted
* from the snapshot of the root node at the time of creation.
*
* ```
* @Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
* @publicApi
*/
export declare class ActivatedRouteSnapshot {
/** The URL segments matched by this route */
url: UrlSegment[];
/**
* The matrix parameters scoped to this route.
*
* You can compute all params (or data) in the router state or to get params outside
* of an activated component by traversing the `RouterState` tree as in the following
* example:
* ```
* collectRouteParams(router: Router) {
* let params = {};
* let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root];
* while (stack.length > 0) {
* const route = stack.pop()!;
* params = {...params, ...route.params};
* stack.push(...route.children);
* }
* return params;
* }
* ```
*/
params: Params;
/** The query parameters shared by all the routes */
queryParams: Params;
/** The URL fragment shared by all the routes */
fragment: string;
/** The static and resolved data of this route */
data: Data;
/** The outlet name of the route */
outlet: string;
/** The component of the route */
component: Type<any> | string | null;
/** The configuration used to match this route **/
readonly routeConfig: Route | null;
/** The root of the router state */
get root(): ActivatedRouteSnapshot;
/** The parent of this route in the router state tree */
get parent(): ActivatedRouteSnapshot | null;
/** The first child of this route in the router state tree */
get firstChild(): ActivatedRouteSnapshot | null;
/** The children of this route in the router state tree */
get children(): ActivatedRouteSnapshot[];
/** The path from the root of the router state tree to this route */
get pathFromRoot(): ActivatedRouteSnapshot[];
get paramMap(): ParamMap;
get queryParamMap(): ParamMap;
toString(): string;
}
/**
* An event triggered at the end of the activation part
* of the Resolve phase of routing.
* @see `ActivationStart`
* @see `ResolveStart`
*
* @publicApi
*/
export declare class ActivationEnd {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* An event triggered at the start of the activation part
* of the Resolve phase of routing.
* @see `ActivationEnd`
* @see `ResolveStart`
*
* @publicApi
*/
export declare class ActivationStart {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* @description
*
* This base route reuse strategy only reuses routes when the matched router configs are
* identical. This prevents components from being destroyed and recreated
* when just the fragment or query parameters change
* (that is, the existing component is _reused_).
*
* This strategy does not store any routes for later reuse.
*
* Angular uses this strategy by default.
*
*
* It can be used as a base class for custom route reuse strategies, i.e. you can create your own
* class that extends the `BaseRouteReuseStrategy` one.
* @publicApi
*/
export declare abstract class BaseRouteReuseStrategy implements RouteReuseStrategy {
/**
* Whether the given route should detach for later reuse.
* Always returns false for `BaseRouteReuseStrategy`.
* */
shouldDetach(route: ActivatedRouteSnapshot): boolean;
/**
* A no-op; the route is never stored since this strategy never detaches routes for later re-use.
*/
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void;
/** Returns `false`, meaning the route (and its subtree) is never reattached */
shouldAttach(route: ActivatedRouteSnapshot): boolean;
/** Returns `null` because this strategy does not store routes for later re-use. */
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
/**
* Determines if a route should be reused.
* This strategy returns `true` when the future route config and current route config are
* identical.
*/
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a route can be activated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, the current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanActivate` function that checks whether the
* current user has permission to activate the requested route.
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivate {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivate(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canActivate: [CanActivateTeam]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide an in-line function with the `canActivate` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canActivate: ['canActivateTeam']
* }
* ])
* ],
* providers: [
* {
* provide: 'canActivateTeam',
* useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export declare interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a child route can be activated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanActivateChild` function that checks whether the
* current user has permission to activate the requested child route.
*
* ```
* class UserToken {}
* class Permissions {
* canActivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanActivateTeam implements CanActivateChild {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canActivateChild(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
* return this.permissions.canActivate(this.currentUser, route.params.id);
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'root',
* canActivateChild: [CanActivateTeam],
* children: [
* {
* path: 'team/:id',
* component: TeamComponent
* }
* ]
* }
* ])
* ],
* providers: [CanActivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide an in-line function with the `canActivateChild` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'root',
* canActivateChild: ['canActivateTeam'],
* children: [
* {
* path: 'team/:id',
* component: TeamComponent
* }
* ]
* }
* ])
* ],
* providers: [
* {
* provide: 'canActivateTeam',
* useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export declare interface CanActivateChild {
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
/**
* @description
*
* Interface that a class can implement to be a guard deciding if a route can be deactivated.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, current navigation
* is cancelled and a new navigation begins to the `UrlTree` returned from the guard.
*
* The following example implements a `CanDeactivate` function that checks whether the
* current user has permission to deactivate the requested route.
*
* ```
* class UserToken {}
* class Permissions {
* canDeactivate(user: UserToken, id: string): boolean {
* return true;
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
*
* @Injectable()
* class CanDeactivateTeam implements CanDeactivate<TeamComponent> {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canDeactivate(
* component: TeamComponent,
* currentRoute: ActivatedRouteSnapshot,
* currentState: RouterStateSnapshot,
* nextState: RouterStateSnapshot
* ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
* return this.permissions.canDeactivate(this.currentUser, route.params.id);
* }
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canDeactivate: [CanDeactivateTeam]
* }
* ])
* ],
* providers: [CanDeactivateTeam, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide an in-line function with the `canDeactivate` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* canDeactivate: ['canDeactivateTeam']
* }
* ])
* ],
* providers: [
* {
* provide: 'canDeactivateTeam',
* useValue: (component: TeamComponent, currentRoute: ActivatedRouteSnapshot, currentState:
* RouterStateSnapshot, nextState: RouterStateSnapshot) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export declare interface CanDeactivate<T> {
canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
/**
* @description
*
* Interface that a class can implement to be a guard deciding if children can be loaded.
* If all guards return `true`, navigation continues. If any guard returns `false`,
* navigation is cancelled. If any guard returns a `UrlTree`, current navigation
* is cancelled and a new navigation starts to the `UrlTree` returned from the guard.
*
* The following example implements a `CanLoad` function that decides whether the
* current user has permission to load requested child routes.
*
*
* ```
* class UserToken {}
* class Permissions {
* canLoadChildren(user: UserToken, id: string, segments: UrlSegment[]): boolean {
* return true;
* }
* }
*
* @Injectable()
* class CanLoadTeamSection implements CanLoad {
* constructor(private permissions: Permissions, private currentUser: UserToken) {}
*
* canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {
* return this.permissions.canLoadChildren(this.currentUser, route, segments);
* }
* }
* ```
*
* Here, the defined guard function is provided as part of the `Route` object
* in the router configuration:
*
* ```
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* loadChildren: 'team.js',
* canLoad: [CanLoadTeamSection]
* }
* ])
* ],
* providers: [CanLoadTeamSection, UserToken, Permissions]
* })
* class AppModule {}
* ```
*
* You can alternatively provide an in-line function with the `canLoad` signature:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'team/:id',
* component: TeamComponent,
* loadChildren: 'team.js',
* canLoad: ['canLoadTeamSection']
* }
* ])
* ],
* providers: [
* {
* provide: 'canLoadTeamSection',
* useValue: (route: Route, segments: UrlSegment[]) => true
* }
* ]
* })
* class AppModule {}
* ```
*
* @publicApi
*/
export declare interface CanLoad {
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
/**
* An event triggered at the end of the child-activation part
* of the Resolve phase of routing.
* @see `ChildActivationStart`
* @see `ResolveStart`
* @publicApi
*/
export declare class ChildActivationEnd {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* An event triggered at the start of the child-activation
* part of the Resolve phase of routing.
* @see `ChildActivationEnd`
* @see `ResolveStart`
*
* @publicApi
*/
export declare class ChildActivationStart {
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot;
constructor(
/** @docsNotRequired */
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
/**
* Store contextual information about the children (= nested) `RouterOutlet`
*
* @publicApi
*/
export declare class ChildrenOutletContexts {
private contexts;
/** Called when a `RouterOutlet` directive is instantiated */
onChildOutletCreated(childName: string, outlet: RouterOutlet): void;
/**
* Called when a `RouterOutlet` directive is destroyed.
* We need to keep the context as the outlet could be destroyed inside a NgIf and might be
* re-created later.
*/
onChildOutletDestroyed(childName: string): void;
/**
* Called when the corresponding route is deactivated during navigation.
* Because the component get destroyed, all children outlet are destroyed.
*/
onOutletDeactivated(): Map<string, OutletContext>;
onOutletReAttached(contexts: Map<string, OutletContext>): void;
getOrCreateContext(childName: string): OutletContext;
getContext(childName: string): OutletContext | null;
}
/**
* Converts a `Params` instance to a `ParamMap`.
* @param params The instance to convert.
* @returns The new map instance.
*
* @publicApi
*/
export declare function convertToParamMap(params: Params): ParamMap;
/**
*
* Represents static data associated with a particular route.
*
* @see `Route#data`
*
* @publicApi
*/
export declare type Data = {
[name: string]: any;
};
/**
* @description
*
* A default implementation of the `UrlSerializer`.
*
* Example URLs:
*
* ```
* /inbox/33(popup:compose)
* /inbox/33;open=true/messages/44
* ```
*
* DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
* colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
* specify route specific parameters.
*
* @publicApi
*/
export declare class DefaultUrlSerializer implements UrlSerializer {
/** Parses a url into a `UrlTree` */
parse(url: string): UrlTree;
/** Converts a `UrlTree` into a url */
serialize(tree: UrlTree): string;
}
/**
* A string of the form `path/to/file#exportName` that acts as a URL for a set of routes to load.
*
* @see `loadChildrenCallback`
* @publicApi
* @deprecated The `string` form of `loadChildren` is deprecated in favor of the
* `LoadChildrenCallback` function which uses the ES dynamic `import()` expression.
* This offers a more natural and standards-based mechanism to dynamically
* load an ES module at runtime.
*/
export declare type DeprecatedLoadChildren = string;
/**
* @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
*/
export declare type DetachedRouteHandle = {};
/**
* Error handler that is invoked when a navigation error occurs.
*
* 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.
*
* @publicApi
*/
declare type ErrorHandler = (error: any) => any;
/**
* 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/router#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 successfuly.
* * [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
*/
export declare type Event = RouterEvent | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd | Scroll;
/**
* A set of configuration options for a router module, provided in the
* `forRoot()` method.
*
* @see `forRoot()`
*
*
* @publicApi
*/
export declare interface ExtraOptions {
/**
* 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 is required for [server-side rendering](guide/universal) to work. 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;
/**
* 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.
*
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy.
* One of `PreloadAllModules` or `NoPreloading` (the default).
*/
preloadingStrategy?: any;
/**
* Define what the router should do if it receives a navigation request to the current URL.
* Default is `ignore`, which causes the router ignores the navigation.
* This can disable features such as a "refresh" button.
* Use this option to configure the behavior when navigating to the
* current URL. Default is 'ignore'.
*/
onSameUrlNavigation?: 'reload' | 'ignore';
/**
* 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.
*
* ```typescript
* class AppModule {
* constructor(router: Router, viewportScroller: ViewportScroller) {
* router.events.pipe(
* filter((e: Event): e is Scroll => e instanceof Scroll)
* ).subscribe(e => {
* if (e.position) {
* // backward navigation
* viewportScroller.scrollToPosition(e.position);
* } else if (e.anchor) {
* // anchor navigation
* viewportScroller.scrollToAnchor(e.anchor);
* } else {
* // forward navigation
* viewportScroller.scrollToPosition([0, 0]);
* }
* });
* }
* }
* ```
*/
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top';
/**
* 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 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]);
/**
* Defines how the router merges parameters, data, and resolved data from parent to child
* routes. By default ('emptyOnly'), inherits parent parameters only for
* path-less or component-less routes.
*
* Set to 'always' to enable unconditional inheritance of parent parameters.
*
* 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`.
*
*/
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
/**
* A custom handler for malformed URI errors. The handler is invoked when `encodedURI` contains
* invalid character sequences.
* The default implementation is to redirect to the root URL, dropping
* any path or parameter information. The function takes three parameters:
*
* - `'URIError'` - Error thrown when parsing a bad URL.
* - `'UrlSerializer'` - UrlSerializer that’s configured with the router.
* - `'url'` - The malformed URL that caused the URIError
* */
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree;
/**
* 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.
*/
urlUpdateStrategy?: 'deferred' | 'eager';
/**
* Enables a bug fix that corrects relative link resolution in components with empty paths.
* Example:
*
* ```
* const routes = [
* {
* path: '',
* component: ContainerComponent,
* children: [
* { path: 'a', component: AComponent },
* { path: 'b', component: BComponent },
* ]
* }
* ];
* ```
*
* From the `ContainerComponent`, you should be able to navigate to `AComponent` using
* the following `routerLink`, but it will not work if `relativeLinkResolution` is set
* to `'legacy'`:
*
* `<a [routerLink]="['./a']">Link to A</a>`
*
* However, this will work:
*
* `<a [routerLink]="['../a']">Link to A</a>`
*
* In other words, you're required to use `../` rather than `./` when the relative link
* resolution is set to `'legacy'`.
*
* The default in v11 is `corrected`.
*/
relativeLinkResolution?: 'legacy' | 'corrected';
}
/**
* An event triggered at the end of the Guard phase of routing.
*
* @see `GuardsCheckStart`
*
* @publicApi
*/
export declare class GuardsCheckEnd extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
/** @docsNotRequired */
shouldActivate: boolean;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot,
/** @docsNotRequired */
shouldActivate: boolean);
toString(): string;
}
/**
* An event triggered at the start of the Guard phase of routing.
*
* @see `GuardsCheckEnd`
*
* @publicApi
*/
export declare class GuardsCheckStart extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
/** @docsNotRequired */
state: RouterStateSnapshot;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string,
/** @docsNotRequired */
state: RouterStateSnapshot);
toString(): string;
}
/**
* 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 is required
* for [server-side rendering](guide/universal) to work.
* * '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.
*
* The following values have been [deprecated](guide/releases#deprecation-practices) since v11,
* and should not be used for new applications.
*
* * 'enabled' - This option is 1:1 replaceable with `enabledBlocking`.
*
* @see `forRoot()`
*
* @publicApi
*/
export declare type InitialNavigation = 'disabled' | 'enabled' | 'enabledBlocking' | 'enabledNonBlocking';
/**
*
* A function that returns a set of routes to load.
*
* The string form of `LoadChildren` is deprecated (see `DeprecatedLoadChildren`). The function
* form (`LoadChildrenCallback`) should be used instead.
*
* @see `loadChildrenCallback`
* @publicApi
*/
export declare type LoadChildren = LoadChildrenCallback | DeprecatedLoadChildren;
/**
*
* A function that is called to resolve a collection of lazy-loaded routes.
* Must be an arrow function of the following form:
* `() => import('...').then(mod => mod.MODULE)`
*
* For example:
*
* ```
* [{
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
* }];
* ```
*
* @see [Route.loadChildren](api/router/Route#loadChildren)
* @publicApi
*/
export declare type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Observable<Type<any>> | Promise<NgModuleFactory<any> | Type<any> | any>;
/**
* Information about a navigation operation.
* Retrieve the most recent navigation object with the
* [Router.getCurrentNavigation() method](api/router/Router#getcurrentnavigation) .
*
* * *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
*/
export declare type 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: string | UrlTree;
/**
* The initial target URL after being parsed with `UrlSerializer.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.
*
* * 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`.
* * 'popstate'--Triggered by a popstate event.
* * 'hashchange'--Triggered by a hashchange event.
*/
trigger: 'imperative' | 'popstate' | 'hashchange';
/**
* 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;
};
/**
* @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 navigation should be handled.
*
* @see [Router.navigate() method](api/router/Router#navigate)
* @see [Router.navigateByUrl() method](api/router/Router#navigatebyurl)
* @see [Routing and Navigation guide](guide/router)
*
* @publicApi
*/
export declare interface NavigationBehaviorOptions {
/**
* When true, navigates without pushing a new state into history.
*
* ```
* // Navigate silently to /view
* this.router.navigate(['/view'], { skipLocationChange: true });
* ```
*/
skipLocationChange?: boolean;
/**
* When true, navigates while replacing the current state in history.
*
* ```
* // Navigate to /view
* this.router.navigate(['/view'], { replaceUrl: true });
* ```
*/
replaceUrl?: boolean;
/**
* Developer-defined state that can be passed to any navigation.
* Access this value through the `Navigation.extras` object
* returned from the [Router.getCurrentNavigation()
* method](api/router/Router#getcurrentnavigation) while a navigation is executing.
*
* After a navigation completes, the router writes an object containing this
* value together with a `navigationId` to `history.state`.
* The value is written when `location.go()` or `location.replaceState()`
* is called before activating this route.
*
* Note that `history.state` does not pass an object equality test because
* the router adds the `navigationId` on each navigation.
*
*/
state?: {
[k: string]: any;
};
}
/**
* An event triggered when a navigation is canceled, directly or indirectly.
* This can happen when a route guard
* returns `false` or initiates a redirect by returning a `UrlTree`.
*
* @see `NavigationStart`
* @see `NavigationEnd`
* @see `NavigationError`
*
* @publicApi
*/
export declare class NavigationCancel extends RouterEvent {
/** @docsNotRequired */
reason: string;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
reason: string);
/** @docsNotRequired */
toString(): string;
}
/**
* An event triggered when a navigation ends successfully.
*
* @see `NavigationStart`
* @see `NavigationCancel`
* @see `NavigationError`
*
* @publicApi
*/
export declare class NavigationEnd extends RouterEvent {
/** @docsNotRequired */
urlAfterRedirects: string;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
urlAfterRedirects: string);
/** @docsNotRequired */
toString(): string;
}
/**
* An event triggered when a navigation fails due to an unexpected error.
*
* @see `NavigationStart`
* @see `NavigationEnd`
* @see `NavigationCancel`
*
* @publicApi
*/
export declare class NavigationError extends RouterEvent {
/** @docsNotRequired */
error: any;
constructor(
/** @docsNotRequired */
id: number,
/** @docsNotRequired */
url: string,
/** @docsNotRequired */
error: any);
/** @docsNotRequired */
toString(): string;
}
/**
* @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 [Router.navigate() method](api/router/Router#navigate)
* @see [Router.navigateByUrl() method](api/router/Router#navigatebyurl)
* @see [Router.createUrlTree() method](api/router/Router#createurltree)
* @see [Routing and Navigation guide](guide/router)
* @see UrlCreationOptions
* @see NavigationBehaviorOptions
*
* @publicApi
*/
export declare interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {
}
/**
* An event triggered when a navigation starts.
*
* @publicApi
*/
export declare class NavigationStart extends RouterEvent {
/**
* Identifies the call or event that triggered the navigation.
* An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.
*
* @see `NavigationEnd`
* @see `NavigationCancel`
* @see `NavigationError`
*/
navigationTrigger?: 'imperative' | 'popstate' | 'hashchange';
/**
* 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?: 'imperative' | 'popstate' | 'hashchange',
/** @docsNotRequired */
restoredState?: {
[k: string]: any;
navigationId: number;
} | null);
/** @docsNotRequired */
toString(): string;
}
/**
* @description
*
* Provides a preloading strategy that does not preload any modules.
*
* This strategy is enabled by default.
*
* @publicApi
*/
export declare class NoPreloading implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* Store contextual information about a `RouterOutlet`
*
* @publicApi
*/
export declare class OutletContext {
outlet: RouterOutlet | null;
route: ActivatedRoute | null;
resolver: ComponentFactoryResolver | null;
children: ChildrenOutletContexts;
attachRef: ComponentRef<any> | null;
}
/**
* 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
*/
export declare 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[];
}
/**
* A collection of matrix and query URL parameters.
* @see `convertToParamMap()`
* @see `ParamMap`
*
* @publicApi
*/
export declare type Params = {
[key: string]: any;
};
/**
* @description
*
* Provides a preloading strategy that preloads all modules as quickly as possible.
*
* ```
* RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* @publicApi
*/
export declare class PreloadAllModules implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* @description
*
* Provides a preloading strategy.
*
* @publicApi
*/
export declare abstract class PreloadingStrategy {
abstract preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
/**
* The primary routing outlet.
*
* @publicApi
*/
export declare const PRIMARY_OUTLET = "primary";
/**
* Registers a [DI provider](guide/glossary#provider) for a set of routes.
* @param routes The route configuration to provide.
*
* @usageNotes
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @publicApi
*/
export declare function provideRoutes(routes: Routes): any;
/**
*
* How to handle query parameters in a router link.
* One of:
* - `merge` : Merge new with current parameters.
* - `preserve` : Preserve current parameters.
*
* @see `UrlCreationOptions#queryParamsHandling`
* @see `RouterLink`
* @publicApi
*/
export declare type QueryParamsHandling = 'merge' | 'preserve' | '';
/**
* @description
*
* Interface that classes can implement to be a data provider.
* A data provider class can be used with the router to resolve data during navigation.
* The interface defines a `resolve()` method that is invoked when the navigation starts.
* The router waits for the data to be resolved before the route is finally activated.
*
* The following example implements a `resolve()` method that retrieves the data
* needed to activate the requested route.
*
* ```
* @Injectable({ providedIn: 'root' })
* export class HeroResolver implements Resolve<Hero> {
* constructor(private service: HeroService) {}
*
* resolve(
* route: ActivatedRouteSnapshot,
* state: RouterStateSnapshot
* ): Observable<any>|Promise<any>|any {
* return this.service.getHero(route.paramMap.get('id'));
* }
* }
* ```
*
* Here, the defined `resolve()` function is provided as part of the `Route` object
* in the router configuration:
*
* ```
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'detail/:id',
* component: HeroDetailComponent,
* resolve: {
* hero: HeroResolver
* }
* }
* ])
* ],
* exports: [RouterModule]
* })
* export class AppRoutingModule {}
* ```
*
* You can alternatively provide an in-line function with the `resolve()` signature:
*
* ```
* export const myHero: Hero = {
* // ...
* }
*
* @NgModule({
* imports: [
* RouterModule.forRoot([
* {
* path: 'detail/:id',
* component: Hero