Angular Routing: Basics and Navigation

In a traditional website, clicking a link sends a request to the server and loads a completely new HTML page. However, Angular is designed for building Single Page Applications (SPAs). In an SPA, the browser does not reload the entire page. Instead, the Angular Router intercepts the URL change and dynamically swaps out parts of the view. This creates a fluid, app-like experience for the user.

What is Angular Routing?

Angular Routing is a powerful mechanism that allows users to navigate between different views or components of an application based on the URL in the browser address bar. It manages the state of the application and ensures that the UI stays in sync with the URL.

The Routing Flowchart

[ Browser URL Change ] 
          |
          v
[ Angular Router Engine ] <---- [ Route Configuration ]
          |
          v
[ Match Found? ] -- NO --> [ Wildcard/404 Component ]
          |
         YES
          |
          v
[ Load Component into Router-Outlet ]
    

Core Building Blocks of Angular Routing

To implement routing in your application, you need to understand four primary elements:

  • Routes Array: A configuration object that maps a URL path to a specific component.
  • RouterModule: The Angular module that provides the necessary service providers and directives for routing.
  • Router-Outlet: A placeholder directive (<router-outlet></router-outlet>) that tells Angular where to render the matched component.
  • RouterLink: A directive used in HTML templates to link to different routes instead of using the standard href attribute.

Step 1: Configuring the Routes

Typically, routing is configured in a dedicated file named app-routing.module.ts. You define an array of route objects where each object contains a path and the component it should display.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' } // Default route
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 2: Displaying the Route

Once the routes are defined, you need to tell Angular where to display the component. This is done using the router-outlet directive in your main app.component.html file.


<h1>Welcome to My Angular App</h1>
<nav>
  <!-- Navigation links will go here -->
</nav>

<!-- The matched component will appear here -->
<router-outlet></router-outlet>

Step 3: Navigating Between Routes

1. Declarative Navigation (HTML)

To navigate between pages, use the routerLink directive. Avoid using href, as it triggers a full page reload, which defeats the purpose of an SPA.


<nav>
  <ul>
    <li><a routerLink="/home">Home</a></li>
    <li><a routerLink="/about">About Us</a></li>
  </ul>
</nav>

2. Programmatic Navigation (TypeScript)

Sometimes you need to navigate based on logic, such as after a user logs in or submits a form. For this, you use the Router service in your component class.


import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({ ... })
export class LoginComponent {
  constructor(private router: Router) {}

  onLogin() {
    // Logic to authenticate user
    this.router.navigate(['/home']);
  }
}

Real-World Use Case: E-Commerce Dashboard

In a real-world e-commerce application, routing is essential for separating the user experience. You might have a Product List route, a Product Detail route, and a Checkout route. By using routing, the user can use the browser's "Back" and "Forward" buttons to navigate their shopping history without losing the application state.

Common Mistakes to Avoid

  • Forgetting the leading slash: In routerLink, forgetting the slash can sometimes lead to "relative" path issues if not handled correctly.
  • Missing Router-Outlet: If your components aren't showing up, double-check that <router-outlet> is present in your template.
  • Path Order: Angular matches routes from top to bottom. Always place more specific routes (like /about/team) above more general ones or wildcards.
  • Case Sensitivity: By default, Angular routes are case-sensitive. Ensure your links match the configuration exactly.

Interview Notes: Frequently Asked Questions

  • What is the difference between forRoot and forChild? forRoot is used in the main app module to register global providers, while forChild is used in feature modules.
  • What does pathMatch: 'full' do? It ensures that the router only matches the route if the entire URL matches the path exactly. This is crucial for empty paths (redirects).
  • How do you handle 404 pages? By using a wildcard route { path: '**', component: PageNotFoundComponent } at the very end of your routes array.

Summary

Angular Routing transforms a collection of components into a navigable Single Page Application. By defining a Routes array, utilizing the router-outlet, and navigating via routerLink or the Router service, you can create a seamless user experience. Mastering these basics is the first step before moving on to advanced topics like Topic 18: Route Parameters and Topic 19: Route Guards.