Angular › Routing

How would you programmatically navigate a user to a different page after they complete an action, such as submitting a form?

Intermediate

Answer

You inject the Router service and call its navigate method with the path you want to go to, useful right after a successful form submission or login, without relying on the user clicking a link themselves.
import { Router } from '@angular/router';

constructor(private router: Router) {}

onLoginSuccess() {
  this.router.navigate(['/dashboard']);
}
Real-world example A checkout page automatically redirects a customer to an order confirmation page the moment their payment is successfully processed, using the Router service instead of requiring the customer to click a link themselves.

Common follow-ups: How would you navigate back to the previous page a user was on?;What is the difference between navigate and navigateByUrl on the Router service?