Sub topic 8
Navigating from Code with the Router Service
Links handle most navigation, but some navigation has to come from code. Examples include going to a page after a form saves, sending a user somewhere after a timeout, or moving to the next item in a wizard. For these cases you inject the Router service and call one of its navigation methods.
This chapter assumes you know TypeScript, standalone components, the inject() function, and basic Promises and Observables. It also assumes you have read the earlier chapters on route configuration, RouterLink, and route parameters.
The Two Navigation Methods
Router has two methods that start a navigation:
navigate(commands, extras?)takes an array of path segments, the same format as[routerLink]. It builds a URL from those segments, so it suits URLs you assemble from variables.navigateByUrl(url, extras?)takes a complete URL string or aUrlTree. It uses the URL exactly as given, so it suits URLs you already have, such as a stored "return to" address.
Both return a Promise<boolean>. The promise resolves to true when navigation succeeds and false when it fails or is cancelled, for example when a guard blocks it. It rejects if an error is thrown during navigation.
Internally, navigate is a thin wrapper. It turns the commands into a UrlTree with createUrlTree and then hands that tree to navigateByUrl.
A Worked Example
The ProductDetailComponent below gets its :id from a component input, which works because the app registers withComponentInputBinding(). It shows the most common patterns: an absolute navigation with query parameters, a relative navigation, and a navigation to a full URL string.
import { Component, Input, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `
<h2>Product {{ id }}</h2>
<button (click)="back()">Back to home</button>
<button (click)="edit()">Edit</button>
<button (click)="next()">Next product</button>
<button (click)="goToHelp()">Help</button>
`
})
export class ProductDetailComponent {
@Input() id!: string;
private router = inject(Router);
private route = inject(ActivatedRoute);
// Absolute: /home?from=42
back(): void {
this.router.navigate(['/home'], { queryParams: { from: this.id } });
}
// Relative to the current route: /products/42/edit
edit(): void {
this.router.navigate(['edit'], { relativeTo: this.route });
}
// Sibling route: /products/43
async next(): Promise<void> {
const nextId = Number(this.id) + 1;
const ok = await this.router.navigate(['../', nextId], { relativeTo: this.route });
if (!ok) {
console.warn('Navigation to the next product was blocked or cancelled.');
}
}
// A complete URL string, used as-is
goToHelp(): void {
this.router.navigateByUrl('/help#products');
}
}Each item in the commands array is one path segment. Angular converts numbers to strings and URL-encodes each segment for you. That makes ['/products', name] safer than building '/products/' + name by hand: a value containing / or ? stays inside its segment and does not break the URL.
Absolute vs Relative Commands
This is where most bugs with navigate come from. The rules are:
| Commands | `relativeTo` given? | Result from `/products/42` |
|---|---|---|
| `['/home']` | either | `/home` |
| `['home']` | no | `/home` (resolved from the root) |
| `['edit']` | yes, current route | `/products/42/edit` |
| `['../', 43]` | yes, current route | `/products/43` |
| `['../../admin']` | yes, current route | `/admin` |
Inject ActivatedRoute in the routed component itself. If you inject it in a service provided at the root, you get the root route, and relative navigation silently resolves from there.
You can also put matrix parameters in the commands array as an object after a segment. ['/products', 42, { view: 'compact' }] produces /products/42;view=compact. Matrix parameters belong to one segment. Use them only if your app already reads them, because most apps use query parameters.
Navigation Extras
The second argument to navigate is a NavigationExtras object. navigateByUrl accepts a smaller set, NavigationBehaviorOptions. It has no relativeTo, queryParams, or fragment, because the URL you pass already contains those parts.
| Option | `navigate` | `navigateByUrl` | Effect |
|---|---|---|---|
| `relativeTo` | yes | no | Base route for relative commands |
| `queryParams` | yes | no | Sets `?key=value` pairs |
| `queryParamsHandling` | yes | no | `'merge'` keeps existing params, `'preserve'` keeps them unchanged |
| `fragment` | yes | no | Sets `#anchor` |
| `preserveFragment` | yes | no | Keeps the current fragment |
| `replaceUrl` | yes | yes | Replaces the current history entry instead of adding one |
| `skipLocationChange` | yes | yes | Navigates without changing the address bar |
| `state` | yes | yes | Passes data through `history.state` without putting it in the URL |
Here is a filter component that updates its query parameters in place. It uses merge so other parameters such as page survive, and replaceUrl so each keystroke does not add a new history entry.
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-product-filter',
standalone: true,
template: `<input placeholder="Search" (input)="search($any($event.target).value)" />`
})
export class ProductFilterComponent {
private router = inject(Router);
private route = inject(ActivatedRoute);
search(term: string): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { q: term || null },
queryParamsHandling: 'merge',
replaceUrl: true
});
}
}Two details matter here. An empty commands array combined with relativeTo means "stay on this route", so only the query string changes. Setting a parameter to null with merge removes it from the URL.
Passing State Without the URL
state carries data that should not appear in the URL, such as a confirmation message after saving. The data is stored in the browser history entry.
import { Component, OnInit, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-save-button',
standalone: true,
template: `<button (click)="save()">Save</button>`
})
export class SaveButtonComponent {
private router = inject(Router);
save(): void {
this.router.navigateByUrl('/home', { state: { message: 'Product saved' } });
}
}
@Component({
selector: 'app-home',
standalone: true,
template: `<p>{{ message }}</p>`
})
export class HomeComponent implements OnInit {
message = '';
ngOnInit(): void {
this.message = history.state?.message ?? '';
}
}Common Errors and Edge Cases
- Navigating to the same URL does nothing. By default the router ignores a navigation to the URL that is already active, and the promise still resolves. Configure
onSameUrlNavigation: 'reload'(withwithRouterConfig) only if you really need a re-run, and remember that it re-runs guards and resolvers, not the component constructor. - Same route, new parameter, no new component. Going from
/products/42to/products/43reuses the existing component instance. Code that reads the ID only once inngOnInitshows stale data. Component inputs and theparamMapObservable both update. A one-timesnapshotread does not. - Passing a full URL to
navigate.navigate(['/help#products'])encodes#as%23and treats it as part of the path. UsenavigateByUrlfor complete strings, ornavigate(['/help'], { fragment: 'products' }). - Ignoring the promise. A guard can turn a navigation into
falseor redirect it somewhere else. If your code needs to know whether the user actually arrived, for example to close a dialog,awaitthe result. - Navigating in a constructor or during a render cycle. Starting a navigation while another one is running cancels the first one. Trigger navigation from event handlers or after asynchronous work finishes, not from template expressions.
- External URLs. The router only handles routes inside your app. For another site, use
window.location.hrefor a plain<a href>.
Choosing Between Them
Use navigate when you build the destination from pieces such as IDs, relative paths, or query objects. Use navigateByUrl when you already have the full URL, for example a returnUrl query parameter saved before sending the user to log in. If you only need the URL and do not want to navigate yet, call router.createUrlTree(commands, extras) and later pass the result to navigateByUrl, or router.serializeUrl(tree) to get a string.
Exercise
A component routed at /orders/7 calls this.router.navigate(['items']). The user ends up at /items instead of /orders/7/items. Why, and what is the fix?
Show answer
Without relativeTo, router.navigate resolves commands from the root, so ['items'] becomes /items. Inject ActivatedRoute in the routed component and call this.router.navigate(['items'], { relativeTo: this.route }).
Exercise
The URL is /products?page=3&sort=price. Write one navigate call that sets q=lamp, keeps page and sort, stays on the current route, and does not add a history entry.
Show answer
this.router.navigate([], { relativeTo: this.route, queryParams: { q: 'lamp' }, queryParamsHandling: 'merge', replaceUrl: true }); The result is /products?page=3&sort=price&q=lamp.
Exercise
A login page has the query parameter returnUrl=%2Fadmin%2Freports%3Ftab%3D2. After login succeeds, which method should send the user back, and why not the other one?
Show answer
Use this.router.navigateByUrl(returnUrl). The value is already a full URL with a path and a query string. Passing it to navigate as one command would encode the slashes and the question mark into a single path segment, which produces the wrong URL.