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
<nav> <a routerLink="/">Home</a> | <a routerLink="/about">About Us</a> | <!-- RouterLink supports array syntax for paths with segments --><a [routerLink]="['/users', 10]">User 10</a>
</nav>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 <a routerLink="/about" routerLinkActive="active-link">About</a>