ActivatedRoute in Angular

By Arvind Rai, March 11, 2024
On this page we will learn to use ActivatedRoute class in our Angular router application.
1. ActivatedRoute contains the route information of a component loaded in router outlet. It is used to traverse the RouterState tree and extract information from nodes.
2. ActivatedRoute contains the properties to fetch information about a route associated with the component loaded in the outlet. The properties of ActivatedRoute are snapshot, title, url, params, queryParams, fragment, data, outlet, component, routeConfig, root, parent, firstChild, children, pathFromRoot, paramMap, queryParamMap.
3. To get array of URL segments, use url property that gives an array of UrlSegment.
4. To get information of path parameters of route, use params and paramMap.
5. To get information of query parameters of URL, use queryParams and queryParamMap.
6. To get hash fragment of the URL, use fragment property.
7. To get information about children routes, use firstChild and children properties.
8. To get current snapshot of the route, use snapshot property.
9. The instance of ActivatedRoute can be obtained by dependency injection in a component.
constructor(private route: ActivatedRoute) {
10. ActivatedRoute is imported from @angular/router.

1. snapshot

ActivatedRoute.snapshot gives current snapshot of this route. snapshot is the instance of ActivatedRouteSnapshot class. The ActivatedRouteSnapshot contains route information of a component loaded in outlet at a particular moment in time. ActivatedRouteSnapshot is the snapshot of ActivatedRoute at a particular moment in time. The properties of ActivatedRouteSnapshot are title, url, params, queryParams, fragment, data, outlet, component, routeConfig, root, parent, firstChild, children, pathFromRoot, paramMap, queryParamMap.
Find the sample code to use ActivatedRoute.snapshot.
constructor(private route: ActivatedRoute) { }
ngOnInit() {
    const city: string = this.route.snapshot.params['city'];
    const url: string = this.route.snapshot.url.join('');
    const fragment = this.route.snapshot.fragment;
    const tracingId =['tracingId'];

2. title

ActivatedRoute.title is an observable that emits title of the route.
Suppose I have following route configuration.
const routes: Routes = [
		path: 'add-customer',
		component: CustomerComponent,
		title: "Add Customer"
When we navigate to ’/add-customer’ path, we can fetch the value of ‘title’ of the route by subscribing to ActivatedRoute.title.
constructor(private route: ActivatedRoute) { }  
ngOnInit() {
    this.route.title.subscribe(title => {
         console.log(title); // Output - Add Customer

3. url

ActivatedRoute.url is an observable that emits array of UrlSegment matched by this route.
UrlSegment represents a single URL segment. Its properties are path, parameters, parameterMap.
constructor( private route: ActivatedRoute) { }
ngOnInit() {
    this.route.url.subscribe((urlSegments: UrlSegment[]) => {
        urlSegments.forEach((segment: UrlSegment) => {

4. params and paramMap

1. ActivatedRoute.params and ActivatedRoute.paramMap properties are used to access path parameters of the route.
2. ActivatedRoute.params is an observable that emits Params instance on subscribe. Params contains the path parameters and its values.
3. ActivatedRoute.paramMap is an observable that emits ParamMap instance on subscribe. ParamMap is a map that provides values of required and optional path parameters of this route. The methods of ParamMap are has(), get(), and getAll() . We can get all keys as parameter names by using its keys property.

Suppose custCity and custId are path parameters in our route configuration.
const routes: Routes = [
		path: 'customer/:custCity/:custId',
		component: CustomerComponent
Using params :
We can fetch the values of custCity and custId using params as below.
this.route.params.subscribe(params => {
For the route ‘customer/vns/11’, the value of custCity is ‘vns’ and custId is 11.
In his way we can access path parameters using params property. Find the sample code to access path parameters and using them to get customer object in our application.
constructor(private route: ActivatedRoute, private customerService: CustomerService) { }
ngOnInit() {
        switchMap((params: Params) =>
          this.customerService.getCustomer(params['custCity'], params['custId']))
    ).subscribe(customer => console.log(customer));
Using paramMap :
We can fetch the values of custCity and custId using get() method of paramMap as below.
this.route.paramMap.subscribe((map: ParamMap) => {
Find the sample code to fetch path parameters and pass them to service using paramMap.
     switchMap((map: ParamMap) =>
       this.customerService.getCustomer(map.get('custCity'), map.get('custId')))
).subscribe(customer => console.log(customer)); 

5. queryParams and queryParamMap

1. ActivatedRoute.queryParams and ActivatedRoute.queryParamMap both properties are used to fetch query parameters of the URL.
2. ActivatedRoute.queryParams is an observable of Params.
3. ActivatedRoute.queryParamMap is an observable of ParamMap that contains the query parameters and its values as map.

Suppose I have a router link that creates a URL with query parameters.
<a routerLink="/customer/add"
  [queryParams]="{custId: 111, custName: 'Vivek'}">Customer</a> 
Created URL will be as below.
Using queryParams :
On subscribing queryParams, we can fetch query parameters as below.
this.route.queryParams.subscribe((params: Params) => {
    console.log(params['custId']); // Output - 111
    console.log(params['custName']); // Output - Vivek
Find one more example that shows the usage of queryParams. Here we fetch query parameter and pass it to our service.
constructor(private route: ActivatedRoute, private customerService: CustomerService) { }
ngOnInit() {
        switchMap((params: Params) => 
           this.customerService.addCustomer(params['custId'], params['custName']))
    ).subscribe(result => console.log(result));
Using queryParamMap :
On subscribing queryParamMap, we get ParamMap instance. Using its get() method, we can fetch query parameters.
this.route.queryParamMap.subscribe((map: ParamMap) => {
Find one more example to use queryParamMap.
    switchMap((map: ParamMap) => 
       this.customerService.addCustomer(map.get('custId'), map.get('custName')))
).subscribe(result => console.log(result)); 

6. fragment

ActivatedRoute.fragment is an observable that emits URL hash fragment as string.
Suppose we have a router link that creates URL with hash fragment.
<a routerLink="/book/page/11" fragment="bottom">Book</a> 
Created URL:
Use fragment to access hash fragment.
this.route.fragment.subscribe(fragment => console.log(fragment)); 
Output: bottom

7. data is an observable that emits instance of Data on subscribe. Data represents static data associated with a particular route. : We can define our data in route configuration using data property of Route that is accessed by property.
const routes: Routes = [
		path: 'customerDetail',
		component: CustomerDetailComponent,
	        data: {confId: 12, fileName: 'abc.txt'}
] : Use to access route data defined above.
constructor(private route: ActivatedRoute) { }
ngOnInit() { Data) => {
      console.log(data['confId']); // Output - 12
      console.log(data['fileName']); // Output - abc.txt

8. outlet and component

ActivatedRoute.outlet property gives outlet name of the route.
ActivatedRoute.component property gives component name of the route.
const outlet = this.route.outlet;

const component = this.route.component;

9. routeConfig

ActivatedRoute.routeConfig gives configuration used to match this route. It contains instance of Route.
routeConfig: Route | null 
We can access Route information using routeConfig.
const data = this.route.routeConfig?.data;

const path = this.route.routeConfig?.path;

const title = this.route.routeConfig?.title;

10. root and parent

ActivatedRoute.root and ActivatedRoute.parent both contains the instance of ActivatedRoute.
The root property gives the information of root of router state.
The parent property gives the information of the parent of this route in the router state tree.
const root: ActivatedRoute = this.route.root;

const parent: ActivatedRoute | null = this.route.parent;

11. firstChild and children

ActivatedRoute.firstChild : Keeps information of the first child of this route as the instance of ActivatedRoute.
ActivatedRoute.children : Keeps information of children of this route in router state tree as an array of ActivatedRoute instances.
Code snippet for firstChild property.
const firstChild: ActivatedRoute | null = this.route.firstChild;
Code snippet for children property.
const children: ActivatedRoute[] = this.route.children;
children.forEach((child: ActivatedRoute) => {

12. pathFromRoot

ActivatedRoute.pathFromRoot tracks the routes from root path to this route. It contains an array of ActivatedRoute instances.
const pathFromRoot: ActivatedRoute[] = this.route.pathFromRoot;
pathFromRoot.forEach((path: ActivatedRoute) => {

13. Reference


©2024 | Privacy Policy | Contact Us