Angular Tutorial
Routing & Navigation
In a standard multi-page website, moving from Home to Contact involves the browser physically destroying the current page and requesting an entirely new HTML file from a server. Because Angular is a Single Page Application (SPA), the browser NEVER reloads. Instead, the Angular Router intercepts the URL change and dynamically swaps out the required Component instantly!
Configuring the Routes (`app.routes.ts`)
In modern Angular, routing paths are defined in the app.routes.ts file using the Routes array. You define which URL string triggers which Component to appear.
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { PageNotFoundComponent } from './not-found/not-found.component';
export const routes: Routes = [
// 1. Standard Routes
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// 2. Redirects (the root URL '' redirects automatically to '/home')
{ path: '', redirectTo: '/home', pathMatch: 'full' },
// 3. Wildcard (404 Error handler must ALWAYS be last!)
{ path: '**', component: PageNotFoundComponent }
];The <router-outlet>
Once Angular knows the routes, it needs to know where geometrically in the HTML to render the matching component. You place a <router-outlet></router-outlet> tag in your root app.component.html file. Think of it exactly like an empty television screen frame; the Router swaps the channels (Components) inside this tag!
<!-- app.component.html -->
<nav>
<h1>My Site Logo</h1>
</nav>
<hr>
<!-- The Home or About component will magically render here -->
<router-outlet></router-outlet>
<hr>
<footer>Copyright 2026</footer>Navigating via Links (routerLink)
You must never use standard HTML hrefs (<a href="/about">) to navigate inside an Angular app. That forces a hard browser reload, completely bypassing the Angular SPA concept. Instead, you use the routerLink directive!
<!-- ✅ GOOD: Changes view instantly via Angular Router -->
<a routerLink="/home">Home</a>
<a routerLink="/about">About Us</a>
<!-- Highlight the active tab automatically using routerLinkActive! -->
<a routerLink="/about" routerLinkActive="active-class">About Us</a>Navigating via TypeScript
Often, you need to change views dynamically via code (like after a successful login API call). To do this, use Dependency Injection to inject the Router service into your controller:
import { Router } from '@angular/router';
export class LoginComponent {
constructor(private router: Router) {}
onLoginSuccess() {
console.log("Logged in!");
// Push the user to the Dashboard instantly
this.router.navigate(['/dashboard']);
}
}Conclusion
Routing turns your application into a fully navigable platform without severe reloading delays. But what if the user tries to type /dashboard in the URL bar, and they aren't logged in? We prevent that using Route Guards.