Five ways to Pass Variables between components in Angular

Passing Variables Between Components in Angular (Parent, Child, Path Param, Service and Router)

I would show you several way you can pass variables from one component to another in Angular. We would cover the following;

 

  1. Set up and Angular App
  2. Pass Variables from Parent to Child
  3. Pass Variable from Child to Parent
  4. Using State Variable
  5. Using Path Parameters
  6. Pass Variables via a Service

 

1. Setup the Environment

First create a new Angular app. I call it variabledemo. Remember to add routing

Create the parent component. Add the parent route

Create the child component. Add the child route

Remove all the content of the index

Embed the child component into the parent component using the <app-child></app-child> tag.

Test your app!

 

2. Pass Variables from Parent to Child

In the parent component ts file, declare a string variable. I call it parentName. On the ngOnInit() method, I assign it a value “Kindson the Genius”.

So we want the child to use this variable. Somehow, we need to pass this variable to the child component. Then the child component would render the value of this variable to the page.

The child component would receive this variable and in a local variable annotated with @Input annotation.

So declare a local variable in the child component called receivedValue. Annotate it with the @Input annotation.

@Input() receivedValue: String;

 

Now to pass the parent’s parentName variable to the child’s receivedValue variable we add it as an attribute to the app-child markup using the format:

[childVariable] = “parentVariable”

At this point, the value of the parentVariable would then be available to the childVariable as well. So my markup looks like this:

<app-child [receivedValue]="parentName"></app-child>

3. Pass Variable from Child to Parent

Let’s first create the variable to send. I call it valueToSend and initialize¬† it to “The Tech Pro from Child”.

To pass a variable from child to parent, we need something called an emitter. This is what actually does the sending. It is simply a variable(function) of type EventEmitter and would be annotated with @Output.

This variable would be of type event emitter declared like this:

@Output() sender = new EventEmitter();

To actually, send this variable we need to call the emit() method of the EventEmitter variable like so:

Then, in the parent component, we need a function (sort of a receiver) to actually capture what is sent by the child.

So in the parent component create a function receiver like so:

receiver(receivedFromChild:any){
  console.log(receivedFromChild)
}

Then in the html markup, you can then connect the sender(from child) and the receiver(in parent) using this format:

<app-child (sender)="receiver($event)"></app-child>

 

Let’s now see how to pass variables between sibling components on the same level.

 

4. Pass Variables Using State Variable

Let’s first create two more components: child1 and child2

Then we add routing for the two components as well

Then add navigation link to them as well from the parent component.

Now, this is all fine. But we’ll now adjust to be able to navigate using a router.

So add router services the the child components

Also add a button that has a click event and set up the click function. The this function would be like this:

Button Markup

<button type="button" (click)="goto2()"> Go to Child 2</button>

 

Event Handler

  goto2(){
    this.router.navigate(["/child2"])
  }

 

Now we would pass the state variable as a second parameter to the navigate function, like so;

  goto2(){
    this.router.navigate(["/child2"], {state: {data:this.Child1Msg}})
  }

This means that we pass a state variable along with the route to child2

Now we would receive the variable in child2 using history.state.

 

5. Pass Variables Using Path Parameter

In this method, the variable would show up in the url of the request. So let’s pass path parameter from Child to Child1. Let’s call the parameter msg.

First, open the app-routing component and adjust the route to child1 to allow for path parameter. Adjust like so:

{ path: "child1/:msg", component: Child1Component},

 

Next, in the routing code in Child component, adjust the goto function to add the msg value like so:

  goto1(){
    this.router.navigate(["/child1/" + this.valueToSend])
  }

 

Finally in Child1 component, we retrieve this variable by two steps:

1. inject an active route to the component like so:

private route: ActivatedRoute

2. use route.snapshot.params to get the parameter like so:

this.route.snapshot.params.msg

 

6. Pass Variables via a Service

Finally, you may have to pass data using services. Although you may not need this often, but the benefit is that you now have your data preserved in a separate service. So you can already read the value from the service.

In this method, you simply create a service and wire it into the components.

First create a service using ng generate service. I call it proxy.

Here is the content of this service:

export class ProxyService {

  public variable1: String; //This is the variable

  constructor() { }
}

 

So, I’m going to be stopping here, bu I do recommend you watch the video on my YouTube Channel where this is done step by step with some fun.

Admin bar avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *