W3cubDocs

/Angular

Router

class final

A service that provides navigation among views and URL manipulation capabilities.

class Router {
  events: Observable<Event>
  routerState: RouterState
  errorHandler: this.options.errorHandler || defaultErrorHandler
  malformedUriErrorHandler: this.options.malformedUriErrorHandler || defaultMalformedUriErrorHandler
  navigated: boolean
  urlHandlingStrategy: inject(UrlHandlingStrategy)
  routeReuseStrategy: inject(RouteReuseStrategy)
  titleStrategy?: TitleStrategy
  onSameUrlNavigation: OnSameUrlNavigation
  paramsInheritanceStrategy: 'emptyOnly' | 'always'
  urlUpdateStrategy: 'deferred' | 'eager'
  canceledNavigationResolution: 'replace' | 'computed'
  config: Routes
  componentInputBindingEnabled: !!inject(INPUT_BINDER, { optional: true })
  url: string
  lastSuccessfulNavigation: Navigation | null
  initialNavigation(): void
  setUpLocationChangeListener(): void
  getCurrentNavigation(): Navigation | null
  resetConfig(config: Routes): void
  dispose(): void
  createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree
  navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = {...}): Promise<boolean>
  navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
  serializeUrl(url: UrlTree): string
  parseUrl(url: string): UrlTree
  isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean
}

See also

Provided in

Properties

Property Description
events: Observable<Event> Read-Only

An event stream for routing events.

routerState: RouterState Read-Only

The current state of routing in this NgModule.

errorHandler: this.options.errorHandler || defaultErrorHandler Deprecated

A handler for navigation errors in this NgModule.

Deprecated Subscribe to the Router events and watch for NavigationError instead. provideRouter has the withNavigationErrorHandler feature to make this easier.

See also:

malformedUriErrorHandler: this.options.malformedUriErrorHandler || defaultMalformedUriErrorHandler Deprecated

A handler for errors thrown by Router.parseUrl(url) when url contains an invalid character. The most common case is a % sign that's not encoded and is not part of a percent encoded sequence.

Deprecated URI parsing errors should be handled in the UrlSerializer.

See also:

navigated: boolean

True if at least one navigation event has occurred, false otherwise.

urlHandlingStrategy: inject(UrlHandlingStrategy) Deprecated

A strategy for extracting and merging URLs. Used for AngularJS to Angular migrations.

Deprecated Configure using providers instead: {provide: UrlHandlingStrategy, useClass: MyStrategy}.

routeReuseStrategy: inject(RouteReuseStrategy) Deprecated

A strategy for re-using routes.

Deprecated Configure using providers instead: {provide: RouteReuseStrategy, useClass: MyStrategy}.

titleStrategy?: TitleStrategy Deprecated

A strategy for setting the title based on the routerState.

Deprecated Configure using providers instead: {provide: TitleStrategy, useClass: MyStrategy}.

onSameUrlNavigation: OnSameUrlNavigation Deprecated

How to handle a navigation request to the current URL.

Deprecated Configure this through provideRouter or RouterModule.forRoot instead.

See also:

paramsInheritanceStrategy: 'emptyOnly' | 'always' Deprecated

How to merge parameters, data, resolved data, and title from parent to child routes. One of:

  • 'emptyOnly' : Inherit parent parameters, data, and resolved data for path-less or component-less routes.
  • 'always' : Inherit parent parameters, data, and resolved data for all child routes.

Deprecated Configure this through provideRouter or RouterModule.forRoot instead.

See also:

urlUpdateStrategy: 'deferred' | 'eager' Deprecated

Determines when the router updates the browser URL. By default ("deferred"), updates the browser URL after navigation has finished. Set to 'eager' to update the browser URL at the beginning of navigation. You can choose to update early so that, if navigation fails, you can show an error message with the URL that failed.

Deprecated Configure this through provideRouter or RouterModule.forRoot instead.

See also:

canceledNavigationResolution: 'replace' | 'computed' Deprecated

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.

Deprecated Configure this through provideRouter or RouterModule.forRoot instead.

See also:

config: Routes
componentInputBindingEnabled: !!inject(INPUT_BINDER, { optional: true }) Read-Only

Indicates whether the the application has opted in to binding Router data to component inputs.

This option is enabled by the withComponentInputBinding feature of provideRouter or bindToComponentInputs in the ExtraOptions of RouterModule.forRoot.

url: string Read-Only

The current URL.

lastSuccessfulNavigation: Navigation | null Read-Only

The Navigation object of the most recent navigation to succeed and null if there has not been a successful navigation yet.

Methods

Sets up the location change listener and performs the initial navigation.

initialNavigation(): void

Parameters

There are no parameters.

Returns

void

Sets up the location change listener. This listener detects navigations triggered from outside the Router (the browser back/forward buttons, for example) and schedules a corresponding Router navigation so that the correct events, guards, etc. are triggered.

setUpLocationChangeListener(): void

Parameters

There are no parameters.

Returns

void

Returns the current Navigation object when the router is navigating, and null when idle.

getCurrentNavigation(): Navigation | null

Parameters

There are no parameters.

Returns

Navigation | null

Resets the route configuration used for navigation and generating links.

resetConfig(config: Routes): void

Parameters
config Routes

The route array for the new configuration.

Returns

void

Usage Notes

router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);

Disposes of the router.

dispose(): void

Parameters

There are no parameters.

Returns

void

Appends URL segments to the current URL tree to create a new URL tree.

createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree

Parameters
commands any[]

An array of URL fragments with which to construct the new URL tree. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL tree or the one provided in the relativeTo property of the options object, if supplied.

navigationExtras UrlCreationOptions

Options that control the navigation strategy.

Optional. Default is {}.

Returns

UrlTree: The new URL tree.

Usage Notes

// create /team/33/user/11
router.createUrlTree(['/team', 33, 'user', 11]);

// create /team/33;expand=true/user/11
router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);

// you can collapse static segments like this (this works only with the first passed-in value):
router.createUrlTree(['/team/33/user', userId]);

// If the first segment can contain slashes, and you do not want the router to split it,
// you can do the following:
router.createUrlTree([{segmentPath: '/one/two'}]);

// create /team/33/(user/11//right:chat)
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);

// remove the right secondary node
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.createUrlTree(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.createUrlTree(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});

Note that a value of `null` or `undefined` for `relativeTo` indicates that the
tree should be created relative to the root.

Navigates to a view using an absolute route path.

See also:

navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = { skipLocationChange: false }): Promise<boolean>

Parameters
url string | UrlTree

An absolute path for a defined route. The function does not apply any delta to the current URL.

extras NavigationBehaviorOptions

An object containing properties that modify the navigation strategy.

Optional. Default is { skipLocationChange: false }.

Returns

Promise<boolean>: A Promise that resolves to 'true' when navigation succeeds, to 'false' when navigation fails, or is rejected on error.

The following calls request navigation to an absolute path.

router.navigateByUrl("/team/33/user/11");

// Navigate without updating the URL
router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.

See also:

navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>

Parameters
commands any[]

An array of URL fragments with which to construct the target URL. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL or the one provided in the relativeTo property of the options object, if supplied.

extras NavigationExtras

An options object that determines how the URL should be constructed or interpreted.

Optional. Default is { skipLocationChange: false }.

Returns

Promise<boolean>: A Promise that resolves to true when navigation succeeds, to false when navigation fails, or is rejected on error.

The following calls request navigation to a dynamic route path relative to the current URL.

router.navigate(['team', 33, 'user', 11], {relativeTo: route});

// Navigate without updating the URL, overriding the default behavior
router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});

Serializes a UrlTree into a string

serializeUrl(url: UrlTree): string

Parameters
url UrlTree
Returns

string

Parses a string into a UrlTree

parseUrl(url: string): UrlTree

Parameters
url string
Returns

UrlTree

3 overloads...

Show All Hide All
Overload #1

Returns whether the url is activated.

isActive(url: string | UrlTree, exact: boolean): boolean

Deprecated Use IsActiveMatchOptions instead.

  • The equivalent IsActiveMatchOptions for true is {paths: 'exact', queryParams: 'exact', fragment: 'ignored', matrixParams: 'ignored'}.
  • The equivalent for false is {paths: 'subset', queryParams: 'subset', fragment: 'ignored', matrixParams: 'ignored'}.
Parameters
url string | UrlTree
exact boolean
Returns

boolean

Overload #2

Returns whether the url is activated.

isActive(url: string | UrlTree, matchOptions: IsActiveMatchOptions): boolean

Parameters
url string | UrlTree
matchOptions IsActiveMatchOptions
Returns

boolean

Overload #3

isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean

Parameters
url string | UrlTree
matchOptions boolean | IsActiveMatchOptions
Returns

boolean

© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/router/Router