Sub topic 8
Navigating from Code with the Router Service
This chapter assumes you already know how to define routes, use RouterLink, and read route parameters. It shows how to navigate from TypeScript. You need this when the next URL depends on logic, such as after a form is saved, after a login succeeds, or when a user picks an item from a dropdown.
The Router service
The Router service is the object that performs navigation. RouterLink uses it behind the scenes. In your own code you get it with inject(Router) and call one of two methods:
| Method | Input | Best for |
|---|---|---|
| `navigate(commands, extras?)` | An array of path segments | URLs built from variables, and relative navigation |
| `navigateByUrl(url, extras?)` | A full URL string or `UrlTree` | URLs you already have as a whole, such as a saved return URL |
Both methods return a Promise<boolean>. It resolves to true when navigation succeeds and false when a guard or a newer navigation cancels it. It rejects if navigation throws an error.
Navigating with commands
Each array element becomes one URL segment. Angular encodes each element for you, so ['/products', 42] becomes /products/42.
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-product-list',
standalone: true,
template: `
<button (click)="open(42)">Open product 42</button>
<button (click)="openEdit()">Edit (relative)</button>
<button (click)="search('laptop')">Search laptops</button>
<button (click)="goHome()">Home</button>
`
})
export class ProductListComponent {
private router = inject(Router);
private route = inject(ActivatedRoute);
open(id: number): void {
this.router.navigate(['/products', id]);
}
openEdit(): void {
// Resolves 'edit' against the current route instead of the root
this.router.navigate(['edit'], { relativeTo: this.route });
}
search(term: string): void {
this.router.navigate(['/products'], {
queryParams: { q: term, page: 1 },
queryParamsHandling: 'merge'
});
}
async goHome(): Promise<void> {
const ok = await this.router.navigateByUrl('/home', { replaceUrl: true });
if (!ok) {
console.warn('Navigation was blocked or cancelled');
}
}
}These navigation extras come up often:
relativeTosets the route that relative commands start from. Without it,navigateresolves relative paths from the root.queryParamsandfragmentset the part of the URL after?and after#.queryParamsHandling: 'merge'keeps the current query parameters and adds the new ones.'preserve'keeps the current parameters and ignores any new ones.replaceUrl: truereplaces the current browser history entry instead of adding one. This stops the Back button from returning to a page such as a login form.
Common errors
- Putting slashes inside one segment.
navigate(['/products/' + id])usually works. A value that contains/or?gets encoded into a single segment, though, and gives you the wrong URL. Pass each piece as its own array element. - Forgetting
relativeTo.navigate(['edit'])goes to/edit, not to/products/42/edit. - Passing a commands array to
navigateByUrl. That method takes a string or aUrlTree. Usenavigatefor arrays. - Assuming navigation is synchronous. Code that runs right after the call still sees the old route. Wait for the promise when the next step depends on the new route.
Exercise
After saving a form at /products/42/edit, you want to go to /products/42 and stop the Back button from reopening the edit page. Write the call, assuming route is the ActivatedRoute of the edit component.
Show answer
this.router.navigate(['..'], { relativeTo: this.route, replaceUrl: true }); The '..' command moves up one level from the edit route, and replaceUrl replaces the edit page's entry in the browser history.
Exercise
The current URL is /products?q=laptop. What URL do you get from router.navigate(['/products'], { queryParams: { page: 2 } }) with no queryParamsHandling option?
Show answer
/products?page=2. The default replaces the existing query parameters, so q is dropped. Add queryParamsHandling: 'merge' to get /products?q=laptop&page=2.