Passing Data Between Components

We know that all the Angular applications are made up of components; in fact components are the basic building blocks of Angular applications. In a simpler manner we can say component is UI/ Views element along with the mechanism to show an operate on data.

Angular Team defines component as the Patch of the screen that we call  View which declares the reusable building blocks for an application. So, in short, component is anything which is visible to the eyes and which can be reused again and again.

Creating Components

As we are using the Angular CLI we can create the component in one command; if you don’t know how do this we set up the project using CLI. Please visit following link.

 

 

When you are done with the project setup now we are ready to add our new component by using the following command

In my case I will run command ng generate component myfirstcomponent ( This is the name of My component and you can choose your own ) this will generate the following folder structure in your application



When we create the component Angular CLI creates the folder with the name of the component and it adds the files myfirstcomponent. component.ts, myfirstcomponent. component.spec.ts, myfirstcomponent.component.html ,and myfirstcomponent.component.css files in the folder myfirstcomponent.

One more change that we can see is at the AppModule.ts .

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     AppComponent  
  9. } from './app.component';  
  10. import {  
  11.     MyfirstcomponentComponent  
  12. } from. / myfirstcomponent / myfirstcomponent.component ';  
  13. @NgModule({  
  14.     declarations: [  
  15.         AppComponent,  
  16.         MyfirstcomponentComponent  
  17.     ],  
  18.     imports: [  
  19.         BrowserModule  
  20.     ],  
  21.     exports: [AppComponent],  
  22.     providers: [],  
  23.     bootstrap: [AppComponent]  
  24. })  
  25. export class AppModule {}  

As we have One module so far in the application so whenever we add the component in the CLI it adds that component directly in the App Module which is the Root module of the application. It imports the component in the Root Module and adds into the declaration section which contains all the components present in the Module.

Exploring first component

When we look at our first component it adds the snippet like below 

It's an export of the component from the angular core which is needed to mark the class as a component

Next thing which we need to see are,

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-myfirstcomponent',  
  7.     templateUrl: './myfirstcomponent.component.html',  
  8.     styleUrls: ['./myfirstcomponent.component.css']  
  9. })  
  10. export class MyfirstcomponentComponent implements OnInit {  
  11.     name: string = "John Doe";  
  12.     constructor() {}  
  13.     ngOnInit() {}  
  14. }  

Selector

It is a property which tells angular to create an insert of this component whenever it sees the element in the template

Templateurl

It is the URL of the html page which tells Angular what needs to be shown in the UI

So how does it work first Angular sees the selector for the component and it search the selector in the HTML and replaces the template/templateUrl which is rendered in that section. In our case the selector is app-myfirstcomponent and template is the myfirstcomponent.component.html which will be rendered in the Browser.

How to use this component ?

Ok we are done now to add and some basic stuff in View. To use this component we must keep in mind the selector property of the component which in our case is the app-component. To use this just add this line in the app.component.html <app-myfirstcomponent></app-myfirstcomponent> so the code snippet for app.component.html will be like below,
  1. <div style="text-align:center">  
  2.     <h1> {{title}} </h1>  
  3.     <h1>  
  4.         <app-myfirstcomponent></app-myfirstcomponent>  
  5.     </h1>  
  6. </div>  

When we see the template URL it is like below for my product

  1. <p>   
  2.      hello {{name}} your first component works!   
  3. </p>  
So, summing up we can say selector is the name of the component which will be used by the angular to call them inside the html

Passing Data Between Components

Ok we have seen how we create and consume the same component in the application now let’s see how we pass the between the components; as in most of the application we need to share the data between the components

There are basically 4 Ways to pass the data between the components, let's see them one by one

Before that let’s see what we mean by parent and child component. Parent component is the component which acts as the container for other component and sibling is the component which is not container but which is not related
 

Following are the ways we can pass the data between parent and child components, let's see one by one

Parent Component to Child component.

There will be always a need that we should send the data between the parent component and child component to do this. Let’s see step by step how we can achieve this

@Input

This decorator which is present is used to obtain the data from the component. To achieve this I have made changes to the component. Let’s add two component namely master and child in the Application by using ng generate command of the Angular CLI

When the components are added look at the code snippet for the child component (child.component.ts)

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     Input  
  5. } from '@angular/core';  
  6. @Component({  
  7.     selector: 'child',  
  8.     templateUrl: './child.component.html',  
  9.     styleUrls: ['./child.component.css']  
  10. })  
  11. export class ChildComponent implements OnInit {  
  12.     @Input("bindingmessaage") message: string  
  13.     constructor() {}  
  14.     ngOnInit() {}  
  15. }  

Here we have used the @Input decorator for making the message as input; let’s see the syntax of the @Input in detail. Here bindingmessage is present in @Input(bindingmessage) is used as the alias of the message property which can be used in the other components .

Ok so far we have made the message property of the ChildComponent for accepting the Values from the Parent component then how do we assign the values to this variable? For that purpose we must see the parent component (Remember this is Parentè Child interaction ). We must make the Provision in the parent component to set the values of this variable for that change, we must look at the snippet of the Master component

To that we must add the child component to the Master component -- how do we do it ? We have selectors for our use here let's look at the following html(Master.component.html) snippet

Master.component.html

  1. <child bindingmessaage="Message from the Parent Without Binding">  
  2. </child>  

app.component.html

  1. <div id="parent-to-child">  
  2.     <div>  
  3.         <master></master>  
  4.     </div>  
  5. </div>  

This code simply adds the master component in the App component which is our root component an master component in return adds the child component in its template

When we run the application we can see the output as displayed at the start page .

This is child component

This is Message from parent:: Message from the Parent Without Binding

Now to pass the value from the parent component to child component we have to the following changes

Update the Master component (Master.component.ts) to following snippet

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'master',  
  7.     templateUrl: './master.component.html',  
  8.     styleUrls: ['./master.component.css']  
  9. })  
  10. export class MasterComponent implements OnInit {  
  11.     sendgreetingtochild: string = "Data from Parent to child using input decorator";  
  12.     constructor() {}  
  13.     ngOnInit() {}  
  14. }  

And in the child template selector which is present in the master.component.html file as follows

  1. <p>  
  2.    <child [bindingmessaage]="sendgreetingtochild"></child>  
  3. </p>  

What we are doing here is we are assigning the value of the property sendgreetingtochild to the bindingmessage Input of the child component

When we save the file, and see the output we can see the output as follows

This is child component

This is Message from parent:: Data from Parent to child using input decorator

We can see the changed output which is the same where we have assigned the value of the variable in the master.component.ts

To sum up this we can say that in order to pass the value from parent to child follow the below steps

  1. use @input to the properties which we want to assign the value
    @Input("bindingmessaage") message:string

  2. Use the property In the selector of the child component
    <child [bindingmessaage]="sendgreetingtochild"></child>

Passing Data between Child to parent (Using @Output) and Event Emitters

We have seen how we can pass the data between then let’s see passing data between the component using @output an Event Emitters.

In this the child component emits the data to the parent component by using the @output decorator an Event emitter this change can occur on button click or the any data change in between.

To achieve this, we can do the  following things,

  1. Parent should have the provision to receive this message which will be assigned and used
  2. Child should have the variable decorated with @output and a function which will emit this event. And the message we want to send to the parent component.

Let us add two component as follows using ng generate command,

  1. ChildwithoutputandemiterComponent.component.ts This will be our child component
  2. MasterwithoutputandeventemiterComponent.component.ts This will be our master component

In order to see how we can use the @output an event emiters lets modify the child component with the following snippet

  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     Output,  
  5.     EventEmitter  
  6. } from '@angular/core';  
  7. @Component({  
  8.     selector: 'app-childwithoutputandemiter',  
  9.     templateUrl: './childwithoutputandemiter.component.html',  
  10.     styleUrls: ['./childwithoutputandemiter.component.css']  
  11. })  
  12. export class ChildwithoutputandemiterComponent implements OnInit {  
  13.     message: string = "Hello from child"  
  14.     @Output("messagefromchid") emitmessage = new EventEmitter < string > ();  
  15.     EmitValue(): void {  
  16.         this.emitmessage.emit(this.Message)  
  17.     }  
  18.     constructor() {}  
  19.     ngOnInit() {}  
  20. }  

Before understanding the code let's see some basic things we have in this snippet these are @output an the EventEmitter

@Output

It is the attribute which is used when we want to send the data outside the component

This attribute always combined with the Event emitter which can be accessed outside the component . by using the Event passed.

EventEmitters

Event emitter is used in the Angular to emit events in the components.

When we see the code description of the above code we can see that we have used the @Output attribute to the and we have set it to the new EventEmitter also we have method EmitValue which emits the Value of the Message Property to the master component .

Next let's see How does the Master component handle these values

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-masterwithoutputandeventemiter',  
  7.     templateUrl: './masterwithoutputandeventemiter.component.html',  
  8.     styleUrls: ['./masterwithoutputandeventemiter.component.css']  
  9. })  
  10. export class MasterwithoutputandeventemiterComponent implements OnInit {  
  11.     GreetingsFromChild: string = "Initial message at the master.";  
  12.     receivemessage($event): string {  
  13.         this.GreetingsFromChild = $event;  
  14.         return this.GreetingsFromChild;  
  15.     }  
  16.     constructor() {}  
  17.     ngOnInit() {}  
  18. }  

In this what we have done is we have created the function Receive Message which receives the value from the Event emitter whenever change in the Variable occurs . In this function Receivemessafe($event) is the function which receives the value from the child component and assigning it to the messagefromchild of the

To see the Output we have some change with the Child and Parent template let's see one by One

  1. <p>  
  2.    <b>Child component:: </b>  
  3.    <br>  
  4.       <input type="text" [(ngModel)]="message">  
  5.       <button (click)="EmitValue ()" value="Emit Value">Emit Value</button>  
  6.    <br>  
  7.    (click on Button to send the Value to Master component)  
  8. </p>  

This is the child template (html file) which has One input and we can see the EmitValue() from the Child component which will be called whenever the button clicks happen. Another change that we need to do is change at the master component like below

  1. <p> <b> Master component :: </b> <br> <b> {{GreetingsFromChild}}</b> <br>  
  2.     <app-childwithoutputandemiter (messagefromchid)=receivemessage($event)></app-childwithoutputandemiter>  
  3. </p>  

When we look at the code we can see that we have added the child component inside the master component for receiving the output. What we have done is we have assigned the receivemessage($event) to the messagefromchild

This was all about the passing of the data from the parent to the child an child to parent we will see the next methods by using the @viewchild and By using the services in next article

Please run npm Install before Running this project

References

  1. https://angular-2-training-book.rangle.io/handout/components/
  2. https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/#Parent-to-Child-Sharing-Data-via-Input
  3. https://angular.io/guide/quickstart

Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all