33. Navigating Programmatically and declaratively
Angular provides two main ways to handle navigation:
- Declarative: Using the
routerLinkdirective in the template (standard links). - Programmatic: Using the
Routerservice in the component class (triggered by logic).
1. Declarative Navigation (routerLink)
The routerLink directive replaces the standard href attribute on anchor tags.
html
2. Programmatic Navigation (The Router Service)
We inject the Router service into the component/service constructor. This is used when navigation is conditional (e.g., after successful login or form submission).
typescript import { Router } from '@angular/router';
export class LoginComponent {
constructor(private router: Router) { }
handleLogin() { // Assume successful authentication const success = true;
if (success) {
// Navigate to the dashboard path
this.router.navigate(['/dashboard']);
// To navigate back up a level:
// this.router.navigate(['../'], { relativeTo: this.route });
} else {
alert('Login failed!');
}
} }
Router Link Active (routerLinkActive)
To highlight the currently active link (e.g., adding a CSS class), use routerLinkActive.
html About