Angular Router

Angular Router

Angular applications are typically Single-Page Applications (SPAs).

This means the browser window never actually refreshes or loads new HTML pages from the server.

Instead, the Angular Router intercepts URL changes and dynamically injects different components into the existing page!


Configuring Routes

To utilize the router, you must define a map of which URL paths belong to which components.

This configuration is usually kept in a dedicated file named app-routing.module.ts.

Routing Configuration:

const routes: Routes = [
  // When the URL is strictly '/', load the Home component
  { path: '', component: HomeComponent },
  // When the URL is '/profile', load the Profile component
  { path: 'profile', component: ProfileComponent },
  // If the user types a URL that doesn't exist, show 404 error
  { path: '**', component: PageNotFoundComponent }
];

The Router Outlet

Once your routes are configured, you need to tell Angular exactly where to render the components.

You do this by placing a <router-outlet></router-outlet> tag inside your main app.component.html.

Think of the router outlet as a magical blank window; whenever the URL changes, Angular swaps out the content displayed in that window instantly.


Navigation with routerLink

In a traditional website, you navigate between pages using an anchor tag with an href attribute (e.g., <a href="/about">).

However, clicking an href forces the browser to completely reload the page, destroying the SPA experience!

In Angular, you must use the routerLink directive instead.

Navigation Links Example:

<nav>
  <!-- Using routerLink prevents page reloads! -->
  <a routerLink="/">Dashboard</a>
  <a routerLink="/profile">My Profile</a>
</nav>

<!-- The selected page renders here! --> <router-outlet></router-outlet>


Active Link Styling

Angular provides a brilliant helper directive named routerLinkActive.

When you attach this to a link, Angular automatically adds a specific CSS class to the link whenever its route is currently active.

This makes styling highlighted navigation menus effortless!


Exercise 1 of 2

?

What acts as the placeholder on the screen where the active routed component will be injected and displayed?

Exercise 2 of 2

?

Why must you use 'routerLink' instead of standard 'href' attributes when navigating an Angular SPA?