How do you navigate to a route programmatically?
Programmatic navigation to a route is done using the Router service.
To do this:
- Inject
Routerinto the component:
typescript
constructor(private router: Router) {}- Use the
navigate()ornavigateByUrl()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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.