How to Access and Pass Route Parameters in Angular

To access route and query parameters in Angular, use the “ActivatedRoute” service. The ActivatedRoute service provides Observables through which we can subscribe to the values of route params and route query params.

In Angular, we can pass the data as route parameters in two ways. 

  1. Route params(Route parameters)
  2. Route queryParams(Route query parameters)

To pass values between views in Angular, we can use “route parameters.” For example, we can use route params if we pass an ID from one route to another and fetch the id on a component onInit(). In real-world scenarios, based on the userID, we can fetch the user profile detail.

Angular Router provides an ActivatedRoute service that offers different observables through which we can access the URL parameters.

Accessing route parameters was never easy before, but now we have a robust Angular router API available to access the route params and even queryParams.

How to Pass Angular Route params

When we install a new angular project, we must enable the routing. That will create a file called app-routing.module.ts file.

Before defining new routes, let’s create two components.

  1. HomeComponent
  2. ProfileComponent

Type the following command to create Angular components.

ng g c home --skipTests=true
ng g c profile --skipTests=true

We can define all the app-related routes inside that file. So let’s define some routes there.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'profile/:id', component: ProfileComponent }
];

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

You can see that we have defined two routes; on the second route, we have passed a dynamic parameter Id.

Linking to Routes with Parameters

The routerLink directive passes an array that specifies the path and a route parameter. Alternatively, we could navigate to the route programmatically. We will use the routerLink directive to navigate between different views.

Write the following code inside the app.component.html file.

<nav class="navbar navbar-light navbar-expand-lg" style="background-color: #e3f2fd;">
  <div class="container">
    <a routerLink="/" class="navbar-brand" routerLinkActive="active" >AppDividend</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <ng-container>
          <li class="nav-item">
            <a [routerLink] = "['/home']" class="nav-link">
            Home
            </a>
          </li>
          <li class="nav-item">
            <a [routerLink] = "['/profile', 1]" class="nav-link">
            Profile
            </a>
          </li>
         </ng-container>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

To navigate one route to another, we have used the routerLink directive.

In profile routerLink, you can see that we have passed two options.

  1. route pattern
  2. parameter: id

We can access the id inside the profile.component.ts file.

Accessing route params using ActivatedRoute

To access the route parameters of the current URL, use the “ActivatedRoute module.”

Write the following code inside the profile.component.ts file.

// profile.component.ts

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

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      console.log('The id of this route is: ', params.id);
    });
  }
}

In this code, we have imported the ActivatedRoute module.

The profile.component.ts file must read the parameter, then load the profile based on the ID given in the parameter.

The ActivatedRoute service provides the params Observable, which we can subscribe to get the route parameters.

The params property on ActivatedRoute is Observable because the Router may not recreate a component when navigating to the same component.

Save the file and start the angular dev server and go to this URL: http://localhost:4200/profile/10

Open the Chrome dev tools and go to the console part. You will see something like this.

Angular Route Params

You can see in the console that we got the value of id, which is 10.

That is it. This is how you can access the current route parameter in Angular.

How to Pass Angular Route queryParams

To pass query parameters in Angular, you don’t need to define anything while defining the routes in the app-routing.module.ts file as we did in the plain route params. Query parameters mean whatever comes from after the question mark(?) in your URL.

We can pass the query parameters using the routerLink directive and programmatically.

Update the following code inside the app.component.html file.

<ng-container>
      <li class="nav-item">
         <a [routerLink] = "['/home']" [queryParams] = "{success: true}" class="nav-link">
            Home
         </a>
      </li>
      <li class="nav-item">
         <a [routerLink] = "['/profile', 1]" class="nav-link">
            Profile
         </a>
      </li>
</ng-container>

In the above code, you can see that in the home navigation, you can see that we have passed another option called queryParams, which takes an object whose key is success and whose value is true.

Based on this parameter, we can display anything in the view. For example, we can display an alert message based on the success true.

Accessing query params in Angular

To access the queryParams inside the angular component, use the ActivatedRoute service that provides the queryParams Observable, which we can subscribe to get the query parameter values.

Write the following code inside the home.component.ts file.

// home.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  notify: string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      if (params.success === 'true') {
        this.notify = 'You have passed data';
      }
    });
  }
}

You can see that inside the ngOnInit() method, we are subscribing to the query params value and checking for the condition.

We are setting a variable called notify. If we get the success = true, we will set the component variable to notify and display the alert message in the view.

The last step is to display the alert message based on the notification message. So write the following code inside the home.component.html file.

<!-- home.component.html -->

<div *ngIf="notify" class="alert alert-success">
    {{ notify }}
</div>
<p>home works!</p>

You can see that I have used the ngIf directive to display the conditional message based on notify value.

Save the file and go to http://localhost:4200/ and click on the home link; you will see something like this.

Angular route query params

That is it. Remove the ?success=true from the URL, and you will see that the alert message is gone because our condition will be false and won’t display anymore.

This functionality is beneficial when you have to show the message like the user is logged in or logged out. It is beneficial.

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.