1. Home
Angular

Angular Tutorial: A Complete Guide to Creating Single-Page Applications

Master Angular with our concise guide, from setting up your environment to deploying production-ready apps.

  • 8 Lessons
  • 2 Hours
right-top-arrow
6

Angular Routing: A Framework to Create Single-Page Applications

Updated on 16/09/2024421 Views

Introduction

As a novice Angular developer, learning routing will feel like unlocking a new dimension. Mastering router links and parameter passing is similar to discovering hidden pathways, helping create a user journey with precision. Advanced techniques like nested and wildcard routes will elevate the user’s skills, enabling the navigation of complex scenarios. Angular routing is a tool for crafting dynamic and intuitive web experiences.

For creating dynamic online apps, especially single-page applications (SPAs), Angular routing is a well-liked framework. Angular's integrated routing mechanism is one of the main components that makes it effective for SPAs. Developers may control how users navigate within an application with Angular's routing system. It lets users switch between views or components without having to reload the entire page.

How Angular Routing Works?

Angular's routing system is based on the concept of routes, which are essentially mappings between URLs and corresponding views or components within the application. When a user navigates to a specific URL or clicks on a link within the application, Angular's router intercepts the request and determines which component should be displayed based on the configured routes.

Routes in Angular are typically defined using the RouterModule, which is part of Angular's @angular/router package. Developers can define routes in a configuration object, specifying the URL path and the component that should be rendered when that path is matched.

Setting Up Angular Routing

Setting up Angular routing in a new or existing Angular project involves several steps. Below are the instructions for setting up Angular routing.

Create a new Angular project

When starting a new project, we can use the Angular CLI (Command Line Interface) to create an Angular project. Open a terminal or command prompt and run the following command:

ng new my-angular-app

Replace my-angular-app with the name of the project.

Navigate into the project directory

Once the project is created, navigate into the project directory using the following command:

cd my-angular-app

Generate a new routing module

Angular CLI provides a command to generate a new routing module along with the initial configuration. Run the following command in the terminal:

ng generate module app-routing --flat --module=app

This command generates a new module named app-routing and adds it to the app.module.ts file.

Define routes in the routing module

Open the app-routing.module.ts file (located in the src/app directory) in the preferred code editor. Define the routes using the RouterModule.forRoot() method within the @NgModule decorator.

Here's an angular routing example of how to define routes:

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: 'home', component: HomeComponent },

  { path: 'about', component: AboutComponent },

  { path: 'contact', component: ContactComponent },

  // Add more routes here as needed

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }

Add router outlet in the app component

In the app.component.html file (located in the src/app directory), add the <router-outlet></router-outlet> directive. This directive is where app routing in Angular will render the components corresponding to the current route.

<router-outlet></router-outlet>

Add navigation links

In the templates (HTML files), add navigation links using the routerLink directive. For example:

<nav>

  <a routerLink="/home">Home</a>

  <a routerLink="/about">About</a>

  <a routerLink="/contact">Contact</a>

</nav>

Run the Angular application

Finally, we can run our Angular application using the following command:

ng serve

Navigate to http://localhost:4200 in a web browser to see the Angular application with routing set up. We have successfully set up Angular routing in our project. We can now add more routes, components, and navigation as needed to build our application.

Router links play a crucial role in navigating between different routes within an Angular application. They provide a way to create clickable elements in templates, which when clicked, take the user to the specified route. Angular routing allows for programmatic navigation based on user actions or application logic.

Router links are directives provided by Angular's router module that allow for declarative navigation between routes. They are used in HTML templates to create clickable elements such as links or buttons.

Creating router links in templates

We can add routing in Angular using the routerLink directive. This directive takes a route path as its input and generates a link that, when clicked, navigates to the specified route.

<a routerLink="/home">Home</a>

<a routerLink="/about">About</a>

<a routerLink="/contact">Contact</a>

In this example, clicking on the "Home" link will navigate the user to the /home route, clicking on the "About" link will navigate to the /about route, and so on. We can also use router links with route parameters:

<a [routerLink]="['/user', userId]">User Profile</a>

Here, userId is a variable in the component that holds the ID of the user. When clicked, this link navigates to the /user/:id route, where: id is replaced by the actual user ID.

Navigating programmatically

In addition to using router links in templates, we can also navigate programmatically utilizing the Router service provided by Angular.

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

@Component({...})

export class MyComponent {

  constructor(private router: Router) {}

  navigateToAbout() {

    this.router.navigate(['/about']);

  }

}

In this example, the navigateToAbout() method, when called, navigates the user to the /about route programmatically.

Passing Parameters to Routes

In Angular, you can pass data and parameters to routes using route parameters, query parameters, or optional parameters. These mechanisms allow you to make dynamic routing in angular and handle different scenarios, such as displaying user-specific data or filtering content based on user input.

Using route parameters

Angular routes with parameters are part of the route path and allow you to pass data directly within the URL. They are defined in the route configuration using the:paramName syntax.

Defining a route with route parameter

const routes: Routes = [

  { path: 'user/:id', component: UserComponent },

];

Accessing route parameters in component

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

@Component({...})

export class UserComponent {

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(params => {

      console.log(params.id); // Accessing route parameter 'id'

    });

  }

}

Using query parameters

Query parameters are key-value pairs appended to the URL after a question mark. They are useful for passing optional parameters or filtering criteria.

Navigating with query parameters

<a [routerLink]="['/search']" [queryParams]="{ query: 'angular' }">Search Angular</a>

Accessing query parameters in component

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

@Component({...})

export class SearchComponent {

  constructor(private route: ActivatedRoute) {

    this.route.queryParams.subscribe(params => {

      console.log(params.query); // Accessing query parameter 'query'

    });

  }

}

Using optional parameters

Optional parameters are similar to route parameters but are not mandatory for the route to match. They are defined in the route configuration using the /:paramName? syntax.

Defining a route with optional parameter

const routes: Routes = [

  { path: 'product/:id', component: ProductComponent },

  { path: 'product/:id/:name?', component: ProductComponent },

];

In this example, the name parameter is optional.

Accessing optional parameters in component

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

@Component({...})

export class ProductComponent {

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(params => {

      console.log(params.id); // Accessing required route parameter 'id'

      console.log(params.name); // Accessing optional route parameter 'name'

    });

  }

}

Advanced Routing Techniques

Advanced routing techniques in Angular extend beyond basic route configuration and involve more sophisticated strategies for managing navigation and handling various scenarios within an application. Some of these techniques include nested routes, wildcard routes, and route resolvers.

Nested routes:

Nested routing in Angular involves organizing routes in a hierarchical structure, where child routes are nested within parent routes. This allows for more granular control over the application's routing and can help in creating complex navigation flows.

Example:

const routes: Routes = [

  { 

    path: 'dashboard', 

    component: DashboardComponent,

    children: [

      { path: 'overview', component: OverviewComponent },

      { path: 'statistics', component: StatisticsComponent },

      // Other child routes

    ]

  },

  // Other top-level routes

];

In this example, the DashboardComponent serves as the parent route, with OverviewComponent and StatisticsComponent being its child routes.

Wildcard routes:

Wildcard routes, also known as catch-all routes, are used to handle routes that do not match any defined routes. They are useful for displaying custom error pages or handling unknown routes gracefully.

Example:

const routes: Routes = [

  { path: '', redirectTo: '/home', pathMatch: 'full' },

  // Other routes

  { path: '**', component: PageNotFoundComponent } // Wildcard route

];

The ** route will match any URL that doesn't match any other defined route, and the PageNotFoundComponent will be displayed.

Route resolvers:

Route resolvers are used to prefetch data before activating a route. They ensure that necessary data is available before the route is rendered, helping avoid empty or incomplete views.

Example:

@Injectable({

  providedIn: 'root'

})

export class DataResolver implements Resolve<Data> {

  constructor(private dataService: DataService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Data> {

    return this.dataService.getData(route.params.id);

  }

}

In this example, the DataResolver fetches data from a service before activating a route. The resolved data is then available to the component associated with the route.

Conclusion

In this angular routing tutorial, I have discussed everything essential relating to the working, setup, and techniques of angular routing. Angular is a well-liked open-source JavaScript framework for creating web apps. Routing enables users to switch between various views or pages in a client-side web application like an Angular single-page application (SPA) without actually loading a new HTML page from the server. Angular routing in web applications offers various advantages.

FAQs

1. What is Angular routing?

Angular routing is a mechanism provided by the Angular framework for managing navigation within a single-page application (SPA). It allows developers to define routes, which are mappings between URL paths and corresponding Angular components. When a user navigates to a specific URL or clicks on a link, Angular's router intercepts the request and renders the associated component without reloading the entire page.

2. Do I need routing in Angular?

Routing in Angular is not mandatory, but it is highly recommended for most applications, especially those with multiple views or sections. Routing enables the creation of SPAs where users can navigate between different pages or views without full page reloads. It also allows for organizing the application's UI into logical sections and separating concerns between different components. 

3. What is the Angular router strategy?

The Angular router strategy refers to how Angular's router handles navigation and render components. Angular provides different strategies for routing, including:

  • HashLocationStrategy: Uses the URL fragment (hash) to navigate between routes. This strategy is useful for applications deployed on servers that do not support URL rewriting.
  • PathLocationStrategy: Uses the browser's history API to navigate between routes. This strategy produces cleaner URLs without the hash fragment and is the preferred option for modern browsers and server setups.

4. How to create a routing file in Angular?

To create a routing file in Angular, we typically use the Angular CLI (Command Line Interface) to generate a routing module. We can run the following command in our terminal or command prompt:

ng generate module app-routing --flat --module=app

This command generates a new routing module named app-routing.module.ts in the src/app directory and configures it within the AppModule.

5. What are the three pillars of Angular routing?

The three pillars of Angular routing are:

  • Routes Configuration: Defines the routes for the application, specifying the URL paths and corresponding components.
  • Router Outlet: Acts as a placeholder in the application layout where the router renders the component associated with the current route.
  • Router Service: Provides methods and properties for programmatic navigation, route parameters access, and other routing-related functionality.

6. What is the benefit of routing in Angular?

Some of the benefits of routing in Angular are:

  • Enhanced user experience with seamless navigation between views without full page reloads.
  • Better organization of code and separation of concerns by structuring the application into logical sections.
  • Improved SEO (Search Engine Optimization) by providing clean and indexable URLs for each page.
  • Support for lazy routing in Angular, allowing for better performance by loading modules and components only when needed.

7. What is routing in Angular with example?

Routing in Angular involves defining routes that map URL paths to Angular components. For example:

const routes: Routes = [

  { path: 'home', component: HomeComponent },

  { path: 'about', component: AboutComponent },

  { path: 'contact', component: ContactComponent },

];

In this example, /home, /about, and /contact are the URL paths, and HomeComponent, AboutComponent, and ContactComponent are the corresponding Angular components that will be rendered when navigating to these paths.

8. How to enable Angular routing?

To enable routing in Angular, you need to perform the following steps:

  • Create a routing module using the Angular CLI
  • Define routes in the routing module
  • Add the RouterModule to the imports array of the AppModule
  • Use the <router-outlet></router-outlet> directive in the application layout to render routed components
  • Add navigation links using the routerLink directive

9. Can we use multiple router outlets in Angular?

Angular supports multiple router outlets, allowing you to have multiple areas in your application layout where different components can be rendered based on the current route. You can define named outlets in your routing configuration and target them using the router-outlet directive with the name attribute.

10. How to test routing in Angular?

Routing in Angular can be tested using Angular's testing utilities and techniques. You can write unit tests and end-to-end tests to ensure expected routing behavior. For unit testing, you can use Angular's TestBed and mock RouterTestingModule to simulate route navigation and test route configurations.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Need More Help? Talk to an Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...