Routing & Navigation
Angular Programmatic Navigation
Router.navigate changes the route from code — after a successful login, after saving a form, or on a timeout. It accepts the same path array and options as routerLink.
What is Programmatic Navigation in Angular?
Router.navigate changes the route from code — after a successful login, after saving a form, or on a timeout. It accepts the same path array and options as routerLink.
Programmatic Navigation example
TypeScript
private router = inject(Router);
onLoginSuccess(returnUrl?: string): void {
this.router.navigate([returnUrl ?? '/dashboard'], { replaceUrl: true });
}
openJob(id: string): void {
this.router.navigate(['/jobs', id], { queryParams: { from: 'search' } });
}
goBack(): void {
this.location.back(); // injected Location service
}Key points to remember
- navigate takes an array of segments; navigateByUrl takes a complete URL string.
- replaceUrl: true keeps the previous page out of the history stack.
- relativeTo with ActivatedRoute enables relative navigation from a child route.
Common mistakes with Programmatic Navigation
- Building URLs by string concatenation and forgetting to encode a segment.
- Navigating away before an HTTP call completes, cancelling it.
Angular Programmatic Navigation— Interview Questions & FAQs
What is the difference between navigate and navigateByUrl?+
navigate takes an array of path segments and supports relative navigation and query parameter options. navigateByUrl takes one absolute URL string and is always absolute.
