← Back to Angular, page 8

angular-0158 · Easy fresher

What is the difference between routerLink, router.navigate and router.navigateByUrl, and how do you pass parameters with each?

routerLink is for links in templates. router.navigate takes a commands array and supports relative navigation and options. router.navigateByUrl takes one complete URL string and is always absolute. All of them return a promise (navigate and navigateByUrl) or render an anchor with a real href (routerLink).

Full answer

There are three ways to move to another page without a browser reload.

  1. routerLink (template). On an a element it renders a real href, so right click, open in new tab and search engines work. <a [routerLink]="['/courses', course.id]">Open</a> builds /courses/42. Add [queryParams]="{ level: 'easy' }" and fragment="reviews". Prefer it whenever the user clicks a link.
  2. router.navigate(commands, extras) (code). The commands are an array of path pieces: this.router.navigate(['/courses', id], { queryParams: { tab: 'info' } }). It supports relativeTo: this.route for relative paths, and options such as replaceUrl: true (replace the current history entry, useful after login), queryParamsHandling: 'merge' and state.
  3. router.navigateByUrl(url, extras) (code). It takes a full URL string or a UrlTree, such as '/courses/42?tab=info'. It is always absolute. Use it when you already have a complete URL, for example a returnUrl from a query parameter.

Differences in short:

  • Input: commands array versus one string versus a link in the template.
  • Relative navigation: navigate with relativeTo, and routerLink with relative paths such as ../. navigateByUrl has no relative mode.
  • Encoding: with navigate, path pieces are encoded for you, so a name with a slash is safe. With navigateByUrl you must encode the string yourself.

Common usage: after saving a form, await this.router.navigate(['/students']). The promise resolves to true when navigation finished, false when a guard blocked it, and rejects on an error.

Security note: do not pass an unchecked returnUrl to navigateByUrl. Check that it starts with / and not // to avoid redirecting users to another site. The router only handles in-app URLs, but a safe check keeps behaviour predictable.

typescript
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router, RouterLink, Routes } from '@angular/router';

@Component({ selector: 'app-list', template: `list` })
export class ListComponent {}

@Component({ selector: 'app-detail', template: `detail` })
export class DetailComponent {}

@Component({
  selector: 'app-nav',
  imports: [RouterLink],
  template: `<a [routerLink]="['/courses', 42]" [queryParams]="{ level: 'easy' }" fragment="reviews">Open course</a>`,
})
export class NavComponent {
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);

  openWithCommands(id: number): Promise<boolean> {
    return this.router.navigate(['/courses', id], { queryParams: { tab: 'info' } });
  }

  openWithUrl(): Promise<boolean> {
    return this.router.navigateByUrl('/courses/7?tab=notes');
  }

  openRelative(): Promise<boolean> {
    return this.router.navigate(['..'], { relativeTo: this.route });
  }
}

export const routes: Routes = [
  { path: 'courses', component: ListComponent },
  { path: 'courses/:id', component: DetailComponent, canActivate: [() => !inject(Router).url.includes('locked')] },
];

Angular 20.3. A Karma test checks the rendered href of the link, navigates with both methods, and checks the resulting URL, the query parameters and the boolean results. The relative navigation and the blocked navigation were not run.

Key points

  • `routerLink` is for template links and gives a real `href`.
  • `navigate` takes a commands array and supports `relativeTo` and options.
  • `navigateByUrl` takes a complete URL string and is absolute.
  • Both methods return a promise that tells you if navigation succeeded.

Common mistakes

  • Using a button with `(click)` and `navigate` when a plain `routerLink` anchor would do.
  • Passing a string with `navigate` and getting wrong URLs when it contains slashes.
  • Expecting `navigateByUrl` to be relative.

Follow-ups

  • How do you keep existing query params while changing one?
  • What does the promise from `navigate` resolve to?
  • How would you go back to the page the user wanted before login?

Tips

  • Start with when to use each, then differences.
  • Mention that `routerLink` renders a real link.
  • Show `replaceUrl` after login as a real example.

Evaluation rubric

  • Names all three and their inputs.
  • Explains relative navigation and encoding.
  • Knows the promise result and a security caution.