circuit

How To Pass Data From One Component To Another In Angular

How to create Components, Routes, and send/receive data via those Routes in Angular




In this tutorial, we are going to see how to pass data from one component to another component in an Angular application. Before Angular, Server only will handle the data sending and data capturing activity. But in Angular, the data sending and data capturing activity is done by Angular only. We can send data to another page/component using many ways. Few options are listed below.

  1. URL Parameter

  2. Query Parameter

  3. Extras State

This tutorial focuses on the routing parameters. Let’s see them one by one.

URL Parameter

The URL parameters are mostly used for SEO purposes. Just look at the sample URL.

[http://localhost:4200/user/raja](http://localhost:4200/user/raja)

Here the raja will be called the URL parameter. In most applications, this type of URL is used. Now let’s see how to create this type of URL in Angular from scratch.

So, first, create a user component using the below command.

ng g c user

Create a route for the user component in the app.routing.ts file.

const routes: Routes = [
  { path: "", component: HomeComponent },
  { path: "login", component: LoginComponent },
  { path: "user/:userId", component: UserComponent },
  { path: "**", component: ErrorPageComponent },
];

Here the :userId is the placeholder to capture the username. The colon used to represent it is a placeholder. We will capture the value using the placeholder name.

We created a component and created the route for the component. To catch the URL parameter we need the ActivatedRoute class. So import the ActivatedRoute class in the user.component.ts file.

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

Then create a reference variable in the constructor for the ActivatedRoute class.

constructor(private activatedRoute:ActivatedRoute) {

}

Then capture the userId placeholder value using the paramMap in the activatedRoute like below.

this.activatedRoute.paramMap.subscribe((params) => {
  this.userId = params.get("userId"); //+ string to number
});

Please remember. The placeholder name is defined in the routing. So use the same placeholder name while capturing the value.

You can display the userId in the user.component.html like below.

<p>UserId: {{userId}}</p>

We can test the above URL parameter using various ways. Test it by entering the below URL directly in the browser.

[http://localhost:4200/user/raja](http://localhost:4200/user/raja)

Test the same by Navigate to the page( component ) using the Router.

gotoUser();
{
  this.router.navigateByUrl("/user/raja");
}

Test the same by Navigate to the page( component ) using the routerLink.

<a routerLink="/user/raja">URL PARAM</a>

All the testing methods will show the raja as output in the browser. Now we are very clear about how to send and receive data using the URL parameter. Next, we will see how to handle the query parameters.

Query Parameter

Example URL for Query parameter given below.

[http://localhost:4200/user/raja?souce=Google&page_id=10](http://localhost:4200/user/raja?souce=Google&page_id=10)

Here the source and page_id are the Query parameters. We can capture these data using the same ActivatedRoute class.

this.source = this.activatedRoute.snapshot.queryParamMap.get("source");

You can display the source in the user.component.html like below. I am taking only one query parameter. You can use the N number of the query parameter.

<p>Source: {{source}}</p>

We can test the above URL parameter using various ways. Test it by entering the below URL in the browser.

[http://localhost:4200/user/raja?source=Application](http://localhost:4200/user/raja?source=Application)

Navigate to the page/component using the Router.

this.router.navigate(["/user/raja"], {
  queryParams: { source: "Application" },
});

Navigate to the page/component using the routerLink.

<a [routerLink]="['/user/raja']" [queryParams]="{ source: 'Application'}">Query PARAM</a>

All the testing approach will show the application as the output in the browser. Here I implemented the query parameter along with the URL parameter. However, the URL and Query parameters are independent. No need to put the Query parameter after the URL parameter.

Extras State

If you want to send a bunch of data without showing them in the URL, then the extras state option is used in the routing.

Import the NavigationExtras class in your home.component.ts file.

import { NavigationExtras } from "@angular/router";

Example Code for Sending Data using extras state.

gotoUser2();
{
  let user = { name: "Raja", age: 20, email: "raja@mail.com" };
  let navigationExtras: NavigationExtras = {
    state: {
      user: user,
    },
  };
  this.router.navigate(["/user/raja"], navigationExtras);
}

Here we passing the data under the state option. And the parameter name is user. You can capture the data using the parameter name user.

To catch the data, we need the Router class. So import the Router class to the user.component.ts file.

import { Router } from "@angular/router";

Example Code for Capturing data using extras state.

if (this.router.getCurrentNavigation().extras.state) {
  let user = this.router.getCurrentNavigation().extras.state.user;
  console.log(user);
}

The Extras state is a great option for sending and receiving data without showing them in the browser. But it had one big disadvantage. If we refresh the page, the extras state data will disappear. We can not capture it. So think about this problem before implementing it in your application and how you are going to handle this situation.

Full Source Code: bharathirajatut/angular-examples

Summary

In this tutorial, you learned the various ways to send data in Angular route from one component to another component and how to receive it also. This tutorial will be very useful for beginners in Angular applications.

So far we have seen the following topics.

  1. How to create a URL parameter and how to send, receive data in the URL parameter.

  2. How to create a Query parameter and how to send, receive data in the URL parameter.

  3. How to create an Extras State parameter and how to send, receive data in the URL parameter. And the disadvantage in the extras state.

Some developers will use the local storage to send and receive data between the pages. You can try the local storage if you want. The local storage will be a solution for extras state if the receiving page refreshes. We can store the extras state data in the local storage and if the page is refreshed, then we can get the data from local storage instead of extras state.

Hope you like this tutorial. Stay tuned for more articles.

Thank you for reading this article.




Continue Learning