Angular / Angular Routing and Navigation

Passing and Retrieving Route Parameters

This tutorial will help you understand how to pass and retrieve parameters between routes in Angular. You'll learn how to pass parameters in the URL and retrieve them using Activa…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains configuring routes and enabling navigation in Angular applications.

1. Introduction

This tutorial aims to guide you through the process of passing and retrieving route parameters in Angular. By the end of this tutorial, you will be able to pass parameters between routes and retrieve them using ActivatedRoute.

You will learn:

  • How to pass parameters in the URL
  • How to retrieve these parameters using ActivatedRoute

Prerequisites:

  • Basic understanding of Angular
  • Familiarity with TypeScript

2. Step-by-Step Guide

In Angular, we can pass parameters through the URL and retrieve them in the component using ActivatedRoute. This is extremely useful when we want to pass data between routes.

First, we need to define our routes and specify where we want to pass the parameters.

Defining Routes

In the app-routing.module.ts file, we define our routes like this:

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

In this example, :id is a placeholder for the parameter we want to pass.

Passing Parameters

When navigating to a route, we can pass the parameter like this:

this.router.navigate(['/product', productId]);

In this example, productId is the parameter we want to pass to the ProductDetailComponent.

Retrieving Parameters

In the ProductDetailComponent, we can retrieve the id parameter using ActivatedRoute like this:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    let id = +params.get('id');
  });
}

In this example, we subscribe to the paramMap observable from ActivatedRoute to get the id parameter.

3. Code Examples

Here are some practical examples.

Example 1: Passing and retrieving a single parameter

In this example, we're passing a single parameter (id) to the ProductDetailComponent.

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ProductDetailComponent } from './product-detail/product-detail.component';

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

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

product-list.component.ts:

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

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
  products = [
    { id: 1, name: 'Product 1' },
    { id: 2, name: 'Product 2' },
    // ...
  ];

  constructor(private router: Router) {}

  ngOnInit() {}

  goToProductDetail(productId) {
    this.router.navigate(['/product', productId]);
  }
}

product-detail.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
  id: number;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.id = +params.get('id');
    });
  }
}

In this example, when a user clicks on a product in the ProductListComponent, the goToProductDetail method is called and the id of the product is passed to the ProductDetailComponent through the URL.

In the ProductDetailComponent, the id is retrieved from the URL in the ngOnInit method.

4. Summary

In this tutorial, you learned how to pass and retrieve parameters between routes in Angular using the URL and ActivatedRoute.

Next steps for learning:

5. Practice Exercises

  1. Create a new Angular application and implement routing. Create two components and pass a parameter from one to the other.

  2. Create a blog application with a list of posts and a detail page for each post. Pass the id of the post from the list to the detail page.

  3. In the blog application, implement a feature to navigate to the next and previous post. Pass the id of the next and previous post to the detail page.

Solutions and explanations for these exercises can be found on the Angular website.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help