Router Outlet and Navigation
Now that we have routes defined, we need two things: a place to display routed components and a way to navigate without page reloads. Enter RouterOutlet and routerLink.
RouterOutlet
The
<router-outlet> is a directive that acts as a placeholder. Angular dynamically loads the component for the current route into this location. Think of it as a TV screen – the channel (route) changes, but the TV (outlet) stays the same.routerLink vs href
If you use regular
href links, the browser will make a full page request, defeating the purpose of an SPA. Instead, Angular provides the routerLink directive for client-side navigation.Here's the correct way to navigate:
<nav>
<ul>
<li><a routerLink="/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/about" routerLinkActive="active">About</a></li>
<li><a routerLink="/contact" routerLinkActive="active">Contact</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
routerLinkActive
The
routerLinkActive directive adds a CSS class when the link is active. This is great for highlighting the current page in navigation menus. Define the class in your CSS:.active {
font-weight: bold;
color: blue;
background-color: lightgray;
}
Programmatic Navigation
Sometimes you need to navigate from code (after form submission, login, etc.). Use the Router service:
import { Router } from '@angular/router';
@Component({...})
export class LoginComponent {
constructor(private router: Router) { }
onSubmit() {
// after successful login
this.router.navigate(['/dashboard']);
// or with relative path
this.router.navigate(['profile'], { relativeTo: this.route });
}
}
Two Minute Drill
- <router-outlet> displays routed components.
- routerLink navigates without page reload.
- routerLinkActive highlights active links.
- Use Router service for programmatic navigation.
- Never use href with Angular routes – it breaks SPA experience.
Need more clarification?
Drop us an email at career@quipoinfotech.com
