Routing and Navigation in Angular

Routing and Navigation in Angular

On May 18, 2024, Posted by , In Angular, With Comments Off on Routing and Navigation in Angular

Table of Contents

In the world of single-page applications (SPAs), Angular stands out for its ability to manage complex routing and navigation with ease. Routing in Angular is more than just moving between pages; it’s about creating a seamless, intuitive navigation experience for users. This article aims to break down the concept of routing in Angular and explain how it enriches web applications.

We are here to help you with Angular Js learning and real-time project based training. Join our Angular JS training in Hyderabad demo and start learning angular course by highly experienced faculty and fully hands-on experience.

What is Routing in Angular?

Routing in Angular refers to the mechanism by which the framework dynamically displays different components or views based on user actions or changes in the browser’s URL. It serves as a navigation system, guiding users through various sections of a single-page application (SPA) seamlessly. For instance, in an e-commerce website built with Angular, routing directs users to the home page, product listings, shopping cart, and checkout process as they navigate through different URLs or interact with navigation links.

See also: Infosys AngularJS Interview Questions

In real-time usage, Angular routing facilitates the creation of intuitive and interactive web applications where users can navigate between different views without full page reloads. For example, in a social media platform developed using Angular, routing enables users to seamlessly transition between their news feed, profile page, messaging interface, and notification panel by clicking on links or typing specific URLs into the browser’s address bar. This dynamic routing capability enhances user experience and ensures efficient content delivery within the application.

Read more about Introduction to Angular: A Beginner’s Guide

Setting Up Routing

To use routing in Angular, you need to define routes in a routing module and configure the Angular Router to associate URLs with specific components.

1. Create Components

First, let’s create a couple of basic components that we’ll navigate between.

ng generate component home
ng generate component about
ng generate component contact

These commands will generate three components: HomeComponent, AboutComponent, and ContactComponent.

2. Define Routes

Next, define the routes in a routing module. Usually, this is done in app-routing.module.ts, which is generated when you create an Angular project with the Angular CLI and select routing.

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

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' }, // Redirect to 'home' when the path is empty
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
  { path: '**', redirectTo: '/home' } // Wildcard route for a 404 page
];

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

Explanation:

Routes Array: The routes array contains route definitions, where each route is an object that maps a path to a component.

{ path: '', redirectTo: '/home', pathMatch: 'full' }: This route redirects an empty path ('') to the home route. The pathMatch: 'full' ensures that the full URL is matched.

{ path: 'home', component: HomeComponent }: This route maps the home path to the HomeComponent.

{ path: '**', redirectTo: '/home' }: The wildcard route ('**') catches all undefined routes and redirects them to the home path, effectively handling 404 errors.

RouterModule.forRoot(): This method sets up the router with the specified routes. The forRoot method is used because this is the root module configuration.

See also: Infosys React JS Interview Questions

3. Add Router Outlet

The RouterOutlet directive acts as a placeholder where the routed components are displayed. It should be added to your main application template, usually in app.component.html.

<nav>
  <a routerLink="/home" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
  <a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>

<router-outlet></router-outlet>

Explanation:

  • routerLink: The routerLink directive is used to navigate to a specific route. It binds the route to the corresponding link, allowing navigation without reloading the page.
  • routerLinkActive: This directive applies a CSS class (active in this case) to the link when its route is active.
  • router-outlet: The router-outlet directive is where the router dynamically loads the components based on the current route.

4. Enable Router in App Module

Ensure that your AppModule includes the AppRoutingModule so that the router configuration is available throughout your application.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Explanation:

The AppRoutingModule is imported into the AppModule to ensure that routing is configured and available in the application.

Read more about Data Binding in Angular: Simplifying UI and Logic Interaction

Running the Application

Once everything is set up, you can run your application using ng serve. Open your browser and navigate to http://localhost:4200. You should be able to click on the navigation links to switch between the Home, About, and Contact views without reloading the page.

Why is Routing Important in Angular?

Enhanced User Experience

Routing plays a crucial role in enhancing the user experience of Angular applications. By providing clear navigation paths, users can intuitively traverse through different sections of the application, leading to a smoother and more enjoyable interaction. Well-defined routes guide users seamlessly from one view to another, reducing confusion and enhancing usability.

Here’s a code snippet example that demonstrates how routing enhances the user experience in an Angular application by providing clear navigation paths:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';

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

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<!-- app.component.html -->
<nav>
  <a routerLink="/home" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About Us</a>
  <a routerLink="/services" routerLinkActive="active">Services</a>
</nav>

<router-outlet></router-outlet>

Explanation:

  • Enhanced Navigation: The routerLink directives in the navigation bar allow users to easily navigate between the “Home,” “About Us,” and “Services” pages without refreshing the page, providing a seamless experience.
  • User Experience: By defining clear routes and corresponding components, the user can intuitively navigate through different sections of the application. This reduces confusion and helps guide the user through the application, enhancing overall usability.

When users click on the “Home,” “About Us,” or “Services” links, the corresponding components are displayed in the router-outlet, creating a smooth transition between views without reloading the entire page. This contributes to a more interactive and engaging user experience, as the application feels more responsive and dynamic.

Read more: Services and Dependency Injection in Angular

Single Page Application Behavior

Angular applications often follow the Single Page Application (SPA) architecture, where content is dynamically loaded without full page reloads. Routing enables this behavior by dynamically swapping components based on the requested URL, providing a fluid and responsive user experience. This approach minimizes page load times and offers a more interactive browsing experience akin to native desktop or mobile applications.

Here’s a code snippet example that illustrates how Angular’s routing supports Single Page Application (SPA) behavior, allowing dynamic component loading without full page reloads:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ProfileComponent } from './profile/profile.component';
import { SettingsComponent } from './settings/settings.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'profile', component: ProfileComponent },
  { path: 'settings', component: SettingsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<!-- app.component.html -->
<nav>
  <a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
  <a routerLink="/profile" routerLinkActive="active">Profile</a>
  <a routerLink="/settings" routerLinkActive="active">Settings</a>
</nav>

<router-outlet></router-outlet>

Explanation:

  • Single Page Application (SPA) Behavior: In this example, routing is used to load different components (Dashboard, Profile, Settings) based on the URL, without reloading the entire page. This dynamic component swapping mimics the behavior of a traditional desktop or mobile application, providing a seamless and responsive user experience.
  • Dynamic Content Loading: The router-outlet directive acts as a placeholder for the dynamically loaded components. When a user navigates to a different route (e.g., /profile or /settings), Angular replaces the content within router-outlet with the corresponding component, without refreshing the page.
  • Improved User Experience: This approach minimizes page load times and enhances interactivity, making the application feel faster and more fluid, much like a native app.

When users click on the “Dashboard,” “Profile,” or “Settings” links, Angular dynamically loads the respective component in the router-outlet, providing the smooth, uninterrupted experience characteristic of SPAs. This enhances the overall usability and responsiveness of the application, as users can navigate between sections quickly and efficiently without the delays associated with full page reloads.

Read more about Directives in Angular

Proper routing implementation empowers users to bookmark or share URLs that correspond to specific states or views within the application. This functionality is instrumental in preserving user context and facilitating seamless navigation, even when users revisit the application through bookmarks or shared links. Additionally, it enables search engine indexing of different application states, improving discoverability and accessibility.

Here’s a code snippet example that demonstrates how Angular routing enables bookmarking and sharing of specific views within a Single Page Application (SPA):

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'product/:id', component: ProductDetailComponent }, // Dynamic route with parameter
  { path: 'contact', component: ContactComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<!-- app.component.html -->
<nav>
  <a routerLink="/home" routerLinkActive="active">Home</a>
  <a routerLink="/product/1" routerLinkActive="active">Product 1</a>
  <a routerLink="/product/2" routerLinkActive="active">Product 2</a>
  <a routerLink="/contact" routerLinkActive="active">Contact Us</a>
</nav>

<router-outlet></router-outlet>

Setting Up Angular Routing

Routing is a critical feature in Angular that allows developers to create Single Page Applications (SPAs) with dynamic views. By setting up routing, you can navigate between different parts of your application without reloading the page, providing a seamless and efficient user experience. This guide will walk you through the process of setting up routing in an Angular application, starting with creating a new Angular project and then configuring the routing module.

1. Create an Angular Application

To begin, you need to set up a new Angular application. The Angular CLI (Command Line Interface) makes this process straightforward by automating the setup and configuration of your project. Follow these steps:

Run the Angular CLI Command: To create a new Angular project, execute the following command:

Open Your Terminal or Command Prompt: Start by opening your terminal (on macOS or Linux) or command prompt (on Windows).

ng new my-app

Explanation: The ng new my-app command initializes a new Angular application named my-app. During this process, the CLI will prompt you to answer a few configuration questions, such as whether you want to include Angular routing and which stylesheet format (CSS, SCSS, etc.) you prefer. You can choose to include routing from the start, which will automatically configure the initial routing setup for you. If you opt not to include routing initially, you can always add it later.

Project Structure: Once the command has finished executing, a new directory named my-app will be created. Inside this directory, you’ll find a complete Angular project setup, including all the files and folders necessary to get started. Navigate to this directory to begin working on your application:

cd my-app

Read more about Understanding Components and Modules in Angular

2. Understanding and Importing RouterModule

Angular provides a built-in module called RouterModule to handle routing within your application. The RouterModule is essential for defining and managing routes, which are mappings between URLs and the components that should be displayed when those URLs are accessed. To use routing in your application, you need to import RouterModule into your main application module, usually AppModule, and then configure the routes.

Importing RouterModule: Open the app.module.ts file in your src/app directory. This file typically looks like this after creating a new Angular project:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

To enable routing, you need to import RouterModule and configure it within the imports array of the @NgModule decorator. Here’s how to modify the AppModule to include routing:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router'; // Import RouterModule and Routes
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

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

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes) // Include RouterModule with the defined routes
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Explanation:

  • RouterModule and Routes: The RouterModule is imported along with Routes from @angular/router. Routes is an array of route definitions that map paths (URLs) to the components that should be displayed.
  • Routes Array: The routes array is defined to map the path 'home' to HomeComponent and the path 'about' to AboutComponent. The empty path ('') is redirected to 'home', meaning that when the application starts, it will automatically navigate to the Home view.
  • RouterModule.forRoot(): The RouterModule.forRoot(routes) method initializes the router with the provided routes, setting up the navigation for your application.

Read more about: Forms in Angular: Streamlining User Input and Validation

3. Using RouterOutlet in Templates

Once you have defined your routes in the AppModule, you need to tell Angular where to render the components corresponding to these routes. This is done using the <router-outlet> directive in your main application template, typically app.component.html.

Update app.component.html:

<nav>
  <a routerLink="/home" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
</nav>

<router-outlet></router-outlet>

routerLink: The routerLink directive is used to link to different routes within your application. Clicking these links changes the URL and triggers the Angular router to load the corresponding component.routerLinkActive: This directive adds the active class to the link when the route is active, helping you style the active link differently.router-outlet: The <router-outlet> directive is a placeholder in the template where the routed component will be displayed. Based on the current route, Angular will load the appropriate component and display it within this outlet.

4. Testing the Routing Setup

Now that you’ve set up routing in your Angular application, it’s time to test it out.

Run the Application: Start your Angular development server by running:

ng serve

This command compiles your application and starts a development server, typically accessible at http://localhost:4200.

Navigate Between Views: Open your web browser and navigate to http://localhost:4200. You should see the Home component displayed. Use the navigation links you set up (Home and About) to move between different views. As you click the links, the URL changes, and the corresponding component is loaded into the <router-outlet>.

Test URLs Directly: You can also directly enter URLs like http://localhost:4200/about in your browser’s address bar to see the About component load immediately. This behavior demonstrates the effectiveness of Angular’s routing in creating a seamless SPA experience.

Dynamic Routing and Route Parameters

Angular routing allows for dynamic paths. You can have variable parts in your URL that change depending on the context. For example, a route like { path: 'user/:id', component: UserComponent } can handle paths like /user/1, /user/2, and so on. The :id part is a route parameter that you can access in your component.

Guarding Routes

Sometimes, you might want to restrict access to certain routes or ask users to confirm before navigating away from a route. This is where Route Guards come in. Angular provides several types of guards like CanActivate, CanDeactivate, and Resolve.

Handling 404 and Redirects

You can set up a wildcard route to handle 404 scenarios when a user navigates to a route that doesn’t exist. Similarly, you can redirect routes, like redirecting an empty path to /home.

Conclusion

Routing in Angular is a powerful feature that enhances the functionality and user experience of your web application. It allows for a structured, intuitive navigation system that mimics the behavior of a multi-page application while keeping the advantages of a single-page application. Angular’s routing capabilities are flexible and robust, enabling you to handle simple navigations to complex data-driven routes efficiently. Understanding and implementing routing effectively is key to building sophisticated Angular applications.

Angular JS training in BangaloreAngular JS training in PuneAngular JS training in Delhi
Angular JS training in IndiaAngular JS training in ChennaiAngular JS training in UK
Angular JS training in AustraliaAngular JS training in AhmedabadAngular JS training in Noida
Comments are closed.