0
0
Angularframework~5 mins

Route parameters with ActivatedRoute in Angular

Choose your learning style9 modes available
Introduction

Route parameters let you pass information in the URL. ActivatedRoute helps you read these parameters inside your Angular component.

You want to show details of a specific item based on its ID in the URL.
You need to read user choices or filters from the URL to display data.
You want to create dynamic pages where content changes based on URL parts.
Syntax
Angular
import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    const id = params.get('id');
    // use id here
  });
}

Use paramMap to get parameters safely as strings or null.

Subscribe inside ngOnInit to react to parameter changes.

Examples
Reads the 'userId' parameter from the URL and logs it.
Angular
this.route.paramMap.subscribe(params => {
  const userId = params.get('userId');
  console.log(userId);
});
Gets the 'productId' parameter once without subscribing, useful if parameters won't change.
Angular
const productId = this.route.snapshot.paramMap.get('productId');
Sample Program

This component reads the 'id' parameter from the URL and shows it inside an <h2> tag.

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

@Component({
  selector: 'app-product-detail',
  template: `<h2>Product ID: {{ productId }}</h2>`
})
export class ProductDetailComponent implements OnInit {
  productId: string | null = null;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.productId = params.get('id');
    });
  }
}
OutputSuccess
Important Notes

Always unsubscribe if you subscribe manually to avoid memory leaks, but Angular handles this for route observables.

Use paramMap instead of params for safer parameter access.

Summary

ActivatedRoute helps you read parameters from the URL inside components.

Use paramMap and subscribe to get updated parameters.

This lets you create dynamic pages that change based on URL values.