Open In App

Explain the purpose of ActivatedRoute in Angular

In Angular applications, navigation is a fundamental feature, that helps to move between different views and components easily. The ActivatedRoute service plays an important role in this navigation process, providing valuable information about the current route, including route parameters, query parameters, and other route-specific metadata. In this article, we'll learn more about the ActivatedRoute in detail.

What is ActivatedRoute in Angular?

The ActivatedRoute is a service provided by the Angular Router module. It represents the route associated with the currently loaded component. In Simple words, ActivateRoute provides access to information about the route, including route parameters, query parameters, and route URL segments.

When the user navigates to a different route, The Angular Router module updates the ActivatedRoute instance containing the current route's information. Finally, we can inject the ActivatedRoute into the component's constructor to access the information.

Purpose of ActivatedRoute

The main purposes of the ActivatedRoute service include:

Examples

1: Accessing Route Parameters

In this example, we'll have a list of products and the user can click on any of the products to have a detailed look at the product. Here we'll pass the product ID along with the route and then fetch it in the other module using ActivatedRoute.

Step 1: Create the new Angular project using the following command.

ng new my-app

Folder Structure:

psstruct

project structure

Step 2: Create two components, one that displays the list of products and other that displays the product detail.

ng generate component product-list
ng generate component product-detail

Step 3: Add the following codes in required files.

<!-- app.component.html -->

<router-outlet></router-outlet>
//app.routes.ts

import { Routes } from '@angular/router';
import { ProductListComponent } from './product-list/product-list.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';

export const routes: Routes = [
    { path: '', component: ProductListComponent },
    { path: 'product/:id', component: ProductDetailComponent },
];
//product-list.component.ts

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

@Component({
    selector: 'app-product-list',
    standalone: true,
    imports: [],
    template: `
    <h1>Product List</h1>
    <ul>
      <li (click)="navigateToProduct(1)">Product 1</li>
      <li (click)="navigateToProduct(2)">Product 2</li>
      <li (click)="navigateToProduct(3)">Product 3</li>
    </ul>
  `,
    styleUrl: './product-list.component.css',
})
export class ProductListComponent {
    constructor(private router: Router) { }

    navigateToProduct(productId: number): void {
        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',
    standalone: true,
    imports: [],
    template: `
    <h1>Product Detail</h1>
    <p>Product ID: {{ productId }}</p>
  `,
    styleUrl: './product-detail.component.css',
})
export class ProductDetailComponent implements OnInit {
    productId: number = 0;

    constructor(private route: ActivatedRoute) { }

    ngOnInit(): void {
        this.route.params.subscribe((params) => {
            this.productId = +params['id'];
        });
    }
}

Step 4: Apply all the changes and run the application using the below command.

ng serve

Output:

 ActivatedRoute Example Angular

output for example 1

2: Responding to Route Changes

In this example, we'll see how to respond to the route changes using ActivatedRoute.

Step 1: Create the new Angular project using the following command.

ng new my-app

Step 2: Create two components. The first components is a home component and other one is the route info component.

ng generate component home
ng generate component route-info

Step 3: Add the following codes in required files.

<!-- app.component.html -->

<router-outlet></router-outlet>
//app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { RouteInfoComponent } from './route-info/route-info.component';

export const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'route/routeInfo', component: RouteInfoComponent },
];
//route-info.component.ts

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

@Component({
    selector: 'app-route-info',
    standalone: true,
    imports: [],
    template: `
    <h1>Current Route Information</h1>
    <p>URL: {{ url }}</p>
  `,
    styleUrl: './route-info.component.css',
})
export class RouteInfoComponent {
    url: string = '';

    constructor(private route: ActivatedRoute) {
        this.route.url.subscribe((urlSegments) => {
            this.url = urlSegments.join('/');
        });
    }
}
//home.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { RouteInfoComponent } from '../route-info/route-info.component';

@Component({
    selector: 'app-home',
    standalone: true,
    imports: [],
    template: `
    <h1>GeeksForGeeks</h1>
    <button (click)="navigateToRoute()">Navigate Me</button>
  `,
    styleUrl: './home.component.css',
})
export class HomeComponent {
    constructor(private router: Router) { }

    navigateToRoute(): void {
        this.router.navigate(['route', 'routeInfo']);
    }
}

Step 4: Apply the changes and run the application using the below command.

ng serve

Output:

Angular ActivatedRoute Example - output

output for example 2

Article Tags :