RouterLink • Angular

You can use absolute or relative paths in a link, set query parameters, control how parameters are handled, and keep a history of navigation states.

The first segment name can be prepended with /, ./, or ../.

  • If the first segment begins with /, the router looks up the route from the root of the app.
  • If the first segment begins with ./, or doesn't begin with a slash, the router looks in the children of the current activated route.
  • If the first segment begins with ../, the router goes up one level in the route tree.

Setting and handling query params and fragments

The following link adds a query parameter and a fragment to the generated URL:

<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}"fragment="education"> link to user component</a>

By default, the directive constructs the new URL using the given query parameters. The example generates the link: /user/bob?debug=true#education.

You can instruct the directive to handle query parameters differently by specifying the queryParamsHandling option in the link. Allowed values are:

  • 'merge': Merge the given queryParams into the current query params.
  • 'preserve': Preserve the current query params.

For example:

<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}"queryParamsHandling="merge"> link to user component</a>

queryParams, fragment, queryParamsHandling, preserveFragment, and relativeTo cannot be used when the routerLink input is a UrlTree.

See UrlCreationOptions#queryParamsHandling.

Preserving navigation history

You can provide a state value to be persisted to the browser's History.state property. For example:

<a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">  link to user component</a>

Use Router#currentNavigation to retrieve a saved Signal navigation-state value. For example, to capture the tracingId during the NavigationStart event:

// Get NavigationStart eventsrouter.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {  const navigation = router.currentNavigation();  tracingService.trace({id: navigation.extras.state.tracingId});});

In order to make a custom element work with routerLink, the corresponding custom element must implement the href attribute and must list href in the array of the static property/getter observedAttributes.