Skip to main content

How do you navigate to a route programmatically?

Programmatic navigation to a route is done using the Router service.

To do this:

  1. Inject Router into the component:
typescript
constructor(private router: Router) {}
  1. Use the navigate() or navigateByUrl() method:
typescript
this.router.navigate(['/profile']);

or with parameters:

typescript
this.router.navigate(['/user', userId]);

The difference:

  • navigate() - takes an array of path segments and options;
  • navigateByUrl() - takes a route string.

Both methods do not reload the page and simply update the router-outlet.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.