Angular Routing and Navigation with Examples

Angular is a powerful framework for building single-page applications (SPAs). One of the key features that makes Angular so versatile for SPAs is its routing and navigation system. Angular’s routing allows you to build applications with multiple views and navigation between them, providing a seamless user experience. In this article, we’ll explore Angular’s routing and navigation capabilities with practical examples.

Understanding Angular Routing

Angular’s routing is based on the Angular Router module. This module allows you to define routes for your application, specifying which component to display for each route. When a user interacts with the application, the router listens for URL changes and displays the appropriate component based on the defined routes.

Setting Up Angular Router

To get started with Angular routing, you first need to set up the Angular Router module. You can do this when creating a new Angular application or by adding it to an existing project.

Here’s how you can set up the Angular Router when creating a new Angular application:

ng new my-app
cd my-app
ng generate module app-routing --flat --module=app

This generates an app-routing.module.ts file that will contain your route configurations.

Defining Routes

In the app-routing.module.ts file, you can define the routes for your application. Each route is defined as an object with two main properties:

  • path: The URL path that triggers this route.
  • component: The component to display when the path is matched.

Here’s an example of defining routes:

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
];

In this example, we have defined three routes: the root path, an “about” path, and a “contact” path, each associated with a specific component.

Displaying the Router Outlet

To render the routed components, you need to add a <router-outlet></router-outlet> element to your application’s template. This element acts as a placeholder where the router will insert the component associated with the current route.

Here’s an example of how to use the router outlet in your app.component.html:

<div>
  <h1>My Angular App</h1>
  <router-outlet></router-outlet>
</div>

With this setup, your application is ready for routing and navigation.

Navigating Between Routes

Angular provides various ways to navigate between routes, including:

1. Using RouterLink

You can use the routerLink directive in your templates to navigate to different routes. For example, to create a link to the “about” page, you can use the following code:

<a routerLink="/about">About Us</a>
2. Using the Router Service

You can also navigate programmatically using the Router service. This is useful when navigation is triggered by events or user interactions. Here’s an example of how to navigate to the “contact” page in your component:

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

// ...

constructor(private router: Router) {}

navigateToContact() {
  this.router.navigate(['/contact']);
}

Route Parameters

Often, you’ll need to pass data between routes. Angular’s router supports route parameters, allowing you to pass dynamic values in the URL and retrieve them in the destination component.

Here’s an example of defining a route with a parameter and accessing it in the component:

const routes: Routes = [
  { path: 'products/:id', component: ProductDetailComponent },
];

In this example, the :id is a route parameter. You can access it in the ProductDetailComponent like this:

import { ActivatedRoute } from '@angular/router';

// ...

constructor(private route: ActivatedRoute) {
  this.route.params.subscribe(params => {
    this.productId = params['id'];
  });
}

Nested Routes

Angular allows you to create nested routes, which are routes defined within the context of a parent route. This is useful for building complex applications with hierarchical views.

For example, you can define a parent route for an “admin” section and nest child routes for different admin features.

const routes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    children: [
      { path: 'users', component: UserListComponent },
      { path: 'settings', component: AdminSettingsComponent },
    ],
  },
];

In this example, the “admin” route has two child routes: “users” and “settings.”

Route Guards

Route guards provide a way to protect and control access to specific routes. There are several types of guards in Angular, including:

  • CanActivate: Determines if a route can be activated.
  • CanActivateChild: Determines if child routes can be activated.
  • CanDeactivate: Determines if a route can be deactivated.
  • CanLoad: Prevents lazy-loaded feature modules from loading prematurely.

Route guards are used to enforce authentication, authorization, and other access control logic in your application.

Example Application

Let’s create a simple example application that demonstrates routing and navigation in Angular. We’ll build a product catalog with a list of products and product details pages.

1. Generate Components

ng generate component products
ng generate component product-detail

2. Define Routes

In app-routing.module.ts, define the routes for the products and product detail pages:

const routes: Routes = [
  { path: 'products', component: ProductsComponent },
  { path: 'products/:id', component: ProductDetailComponent },
  { path: '', redirectTo: '/products', pathMatch: 'full' },
];

3. Create Navigation Links

In products.component.html, create navigation links to the product detail pages using routerLink:

<ul>
  <li *ngFor="let product of products">
    <a [routerLink]="['/products', product.id]">{{ product.name }}</a>
  </li>
</ul>

4. Display Product Details

In product-detail.component.ts, retrieve the product ID from the route parameters and display product details:

import { ActivatedRoute } from '@angular/router';

// ...

constructor(private route: ActivatedRoute) {
  this.route.params.subscribe(params => {
    this.productId = params['id'];
    this.product = this.products.find(p => p.id === +this.productId);
  });
}

This is just a simple example to get you started. You can extend and enhance this application to suit your needs.

Conclusion

Angular’s routing and navigation system provides a robust way to build single-page applications with multiple views. Whether you’re building a small website or a complex enterprise application, Angular’s router makes it easy to manage navigation and create a seamless user experience. By defining routes, using route parameters, and protecting routes with guards, you can create dynamic and interactive web applications with ease.

Leave a Reply