AppDividend
Latest Code Tutorials

Angular Route Params: How to Pass Route Params in Angular

0

To access route parameters and query parameters in Angular, use 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)

If we want to pass values between views, then we can use route params. For example, if we’re going to pass an ID from one route to another and fetch the id on a component onInit(), then we can use route params. 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 params are never easy before, but now we have available robust Angular router API through which we can access the route params and even queryParams.

How to Pass Angular Route params

When we install a new angular project, we have to 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 10 components.

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

Now, 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, and 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.

Now, 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

For this example, we have taken static id, but in realtime projects, it will be dynamic from the database.

So, we passed the id as route parameters, and now we can access the id inside the profile.component.ts file.

Accessing route params using ActivatedRoute

To access the route params 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 reason that the params property on ActivatedRoute is an Observable is that the Router may not recreate a component when navigating to the same component.

Now, 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 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 in your URL whatever comes from after question mark(?).

We can pass the query params using the routerLink directive as well as 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 value is true.

Now, 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, and we are subscribing to the query params value and check for the condition.

We are setting a variable called notify. If we get the success = true, then 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 notify 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 ngIf directive to display the conditional message based on notify value.

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

 

Angular route query params

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

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

Conclusion

To pass route params and route query params in Angular, you have to use ActivatedRoute service and use the params observable to get your desired values.  The Angular Router provides robust API so that you can do anything with it.

That is it for this Angular route params tutorial.

Leave A Reply

Your email address will not be published.

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