ActivatedRoute in Angular

In Angular, ActivatedRoute is a service provided by the Angular Router module. It represents the route associated with a component loaded in an outlet at a specific moment in time. It provides information about the route's parameters, data, URL segments, and query parameters. The ActivatedRoute service allows you to access and interact with the current route's state and information. Let's explore how to use ActivatedRoute:

#1 Import ActivatedRoute:

To use ActivatedRoute in your Angular component, you need to import it from the '@angular/router' module.

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

#2 Inject ActivatedRoute:

Next, inject the ActivatedRoute service into your component's constructor using Angular's dependency injection mechanism.

constructor(private route: ActivatedRoute) { }

#3 Access Route Information:

You can then access various properties and methods provided by ActivatedRoute to retrieve information about the current route.

Snapshot:

You can access route snapshot data, including route parameters, query parameters, and URL segments, using the snapshot property.

ngOnInit(): void {
  const id = this.route.snapshot.params['id'];
  const queryParams = this.route.snapshot.queryParams;
  const urlSegments = this.route.snapshot.url;
  // Access other snapshot properties as needed
}

Observables:

You can subscribe to route parameters changes and other route-related events using observables provided by ActivatedRoute.

ngOnInit(): void {
  this.route.params.subscribe(params => {
    const id = params['id'];
    // Handle parameter changes
  });

  this.route.queryParams.subscribe(queryParams => {
    // Handle query parameter changes
  });

  // Subscribe to other route-related events as needed
}

Using Route Data:

You can also access any data associated with the route using the data property of ActivatedRoute.

ngOnInit(): void {
  const routeData = this.route.snapshot.data;
  // Access route data properties
}