Sharing Data Between Component Using Angular V4 And Above

I hope you all are doing well and and have read my previous tutorials . My previous article is about Binding with Angular 4 and above Binding with Angular v4 And Above  in which I have explained about the types of binding which we are using in Angular4. Today I am here with one more article about sharing data between components which is very important for Angular .

It’s a basic need for any application to send the data and play with data and perform the required operations which are necessary according to our requirement.

In Angular mainly we have 4 methods by which we can pass the value from one component to another, either parent child or any component to any component:

  • @Input
  • @Output
  • @ViewChild
  • Through Service

Here, I will explain only three, the fourth one is  about service which I will explain in my later tutorial .

One thing you need to know these above are the decorator which we are using within Angular application .  First thing which come to your mind is, what is Decorator ?

What is Decorator?

Simply you can say the Decorators are functions that receive the decorated object and can make any changes to it  as in @Component({ selector: 'child-comp', templateUrl: 'app.child.component.html', styleUrls:[], }).

In Angular we have the below types of Decorator,

  • Class decorators: @Component and @NgModule
    These are the top level decorators which Angular supports. They allow us to tell Angular that a particular class is a component, or module.
  • Property decorators 
    We are using these type of decorator for properties inside classes as @Input and @Output

    They allow us to decorate specific properties within our classes.
  • Method decorators 
    We are using these type of decorators for methods inside classes, as @HostListener

    Method decorators are  the same as property decorators but we are using them for methods instead. This decorates specific methods within our class with functionality.
  • Parameter decorators
    We are using these types of decorator for parameters inside class constructors as @Inject

We can use Parameter decorators when I will inject a particular component etc into  constructor . The details about it, I will explain my later tutorial.

Now, I am going to explain the number of ways by which we can pass the value within component. In my application I am using app.component as parent and app.child.component as child component as:

@Input

As I told you it’s a decorator which is the type of Property decorator . We can use the @Input decorator as,

app.child.component.ts

  1. //Input decorator for send value from child to parent  
  2.   @Input('parentcount')  
  3.   count: number;  

Here we are using @input decorator for sending the parent value to child so we will use @Input decorator as parentcount in child component and within parent component we will set the parentcount value as:

app.component.html

  1. <child-comp   
  2.           [parentcount]="pcount" <child-comp>  
@Output

It’s a decorator which is also the type of Property decorator and we are using it for sending the child value to parent component using event emitter as in the below I am using @Output decorator change with event emitter number.
  1. //Output decorator for send value from parent to child  
  2.   @Output()  
  3.   change: EventEmitter<number> = new EventEmitter<number>();  

In the parent component html file as app.component.html we will use the method for updating the value by one method  updateFromChild($event) which we will add in parent component html file as:

app.component.html

  1. <child-comp   
  2.           [parentcount]="pcount"   
  3.           (change)="updateFromChild($event)"></child-comp>  

app.component.ts

  1. //Initial value of pcount . I have added p only for parent .  
  2.   pcount: number = 0;  
  3. //for event emitter  
  4.   updateFromChild($event) {  
  5.     debugger;  
  6.     this.pcount++;  
  7.   
  8.   }  

I have also added the reset button in the parent component for resetting the parent value as initial 0 as below:

app.component.html

  1. <button (click)="reset()">Reset count</button>  

app.component.ts

  1. //for rest the value from parent component  
  2.   reset() {  
  3.     this.pcount = 0;  
  4.   }  

In the child component, I have added a button:

Child Component

app.child.component.html

  1. <div class='child-app'>  
  2.   <h2>Child component</h2>  
  3.   <button (click)="updateCount()">Add To Parent</button>  
  4. </div>  

app.child.component.ts

  1. //Output decorator for send value from parent to child  
  2.   @Output()  
  3.   change: EventEmitter<number> = new EventEmitter<number>();  
  4.   
  5.   updateCount() {  
  6.     debugger;  
  7.     this.count++;  
  8.     this.change.emit(this.count);  
  9.   }  

Parent Component

app.component.html

  1. child-comp   
  2.           [parentcount]="pcount"   
  3.           (change)="updateFromChild($event)"></child-comp>  

app.component.ts

  1. //for event emitter  
  2.   updateFromChild($event) {  
  3.     debugger;  
  4.     this.pcount++;  
  5.   
  6.   }  

So , according to the above if we will click on button the updatecount method is called and it runs the this.change.emit(this.count) which calls the updateFromChild method which is the method of parent component for increasing the count value .

@ViewChild

When we have the requirement , I need child value for the parent component so in this case I have one option to use @ViewChild. As in below I am using the Child and Parent component :

Child Component

app.child.component.ts

  1. //added for view child property  
  2.   childMsg: string="Hi I am from child";  

Parent Component

app.component.html

  1. <div>{{Message}} </div>  

app.component.ts

  1. // Here we can see the Message value this.Message='I am from Parent' which I have added   
  2.   //in this parent component   
  3.   ngOnInit() {  
  4.     debugger;  
  5.     this.Message='I am from Parent';  
  6.   
  7.   }  
  8. //Updating value using view child when child view loaded  
  9.   ngAfterViewInit() {  
  10.   
  11.     //  this.Message = this.child.childMsg;  
  12.   }  

Now, with the message we will see the message which I have added in parent component . You can notice here I have commented the code within ngAfterViewInit:

In the above case the output will be,

Output

As I already told you, ngAfterViewInit is the hook  where all the child components are completely loaded and here you can set the value of child property which I have added in child component using View child.

Now I am using @ViewChild for getting the child property in the parent component:

app.child.component.ts

  1. //added for view child property  
  2.   childMsg: string="Hi I am from child";  

app.component.ts

  1. //Viewchild for getting value from child   
  2.   @ViewChild(ChildComponent) child;  
  3.   
  4.   //Updating value using view child when child view loaded  
  5.   ngAfterViewInit() {  
  6.   
  7.     this.Message = this.child.childMsg;  
  8.   }  

As you can see now I have added the code this.Message = this.child.childMsg  which I am using for getting the value of child property “childMsg” and setting the “Message” property of parent component in the ngAfterViewInit because here I can get the child value in the parent component. Now the output will be,

 

The complete code which I have added for the application:

  • app.component.html
    1. <div class="parent-app">  
    2.   <button (click)="reset()">Reset count</button>  
    3.     <div>  
    4.       <h2>Parent component</h2>  
    5.         <div>  
    6.           count from child: {{pcount}}  
    7.         </div>  
    8.       <child-comp   
    9.           [parentcount]="pcount"   
    10.           (change)="updateFromChild($event)"></child-comp>  
    11.     </div>  
    12.       
    13.   </div>  
    14. <div>{{Message}} </div>  
  • app.component.ts
    1. //our root app component  
    2. import { Component, VERSION, OnInit, ViewChild, AfterViewInit } from '@angular/core'  
    3. import { BrowserModule } from '@angular/platform-browser'  
    4. import { ChildComponent } from './app.child.component'  
    5.   
    6. @Component({  
    7.   selector: 'app-root',  
    8.   templateUrl: 'app.component.html',  
    9.   
    10. })  
    11. export class APPComponent implements OnInit, AfterViewInit {  
    12.   constructor() {  
    13.   
    14.   }  
    15.   //Initial value of pcount . I have added p only for parent .  
    16.   pcount: number = 0;  
    17.   
    18.   Message: string = '';  
    19.   
    20.   // Here we can see the Message value this.Message='I am from Parent' which I have added   
    21.   //in this parent component   
    22.   ngOnInit() {  
    23.   
    24.     this.Message = 'I am from Parent';  
    25.   
    26.   }  
    27.   //for event emitter  
    28.   updateFromChild($event) {  
    29.   
    30.     this.pcount++;  
    31.   }  
    32.   
    33.   //for rest the value from parent component  
    34.   reset() {  
    35.     this.pcount = 0;  
    36.   }  
    37.   
    38.   //Viewchild for getting value from child   
    39.   @ViewChild(ChildComponent) child;  
    40.   
    41.   //Updating value using view child when child view loaded  
    42.   ngAfterViewInit() {  
    43.   
    44.     this.Message = this.child.childMsg;  
    45.   }  
    46.   
    47. }  
    48. export class AppModule { }  
  • app.child.component.html
    1. <div class='child-app'>  
    2.   <h2>Child component</h2>  
    3.   <button (click)="updateCount()">Add To Parent</button>  
    4. </div>  
  • app.child.component.ts
    1. import { Component, Input, Output, EventEmitter } from '@angular/core'  
    2.   
    3. @Component({  
    4.   selector: 'child-comp',  
    5.   templateUrl: 'app.child.component.html',  
    6.   
    7. })  
    8.   
    9. export class ChildComponent {  
    10.   
    11.   //Input decorator for send value from child to parent  
    12.   @Input('parentcount')  
    13.   count: number;  
    14.   
    15.   //Output decorator for send value from parent to child  
    16.   @Output()  
    17.   change: EventEmitter<number> = new EventEmitter<number>();  
    18.     
    19. //added for view child property  
    20.   childMsg: string="Hi I am from child";  
    21.   
    22.   updateCount() {  
    23.     debugger;  
    24.     this.count++;  
    25.     this.change.emit(this.count);  
    26.   }  
    27.  
  • style.css for global css.
    1. /* You can add global styles to this file, and also import other style files */  
    2. .parent-app {  
    3.     border: 5px solid #CFF1E1;  
    4.     border-radius: 10px;  
    5.     background-color: #D1BFD4;  
    6.   }  
    7.   
    8.   .child-app{  
    9.     border: 5px solid #CFF1E1;  
    10.     border-radius: 10px;  
    11.     background-color: #E4BDD2;  
    12.     height: 100px;  
    13.   }  

Now one thing is very important to know when you will add the child component or any component you must add a declaration within app.module.ts file which is the main module file in my application. If you don't,  the below error will show,

 
 For resolving the above problem you will add the component name as,

 app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import{HttpModule} from '@angular/http'  
  4.   
  5. import { APPComponent } from './app.component';  
  6. // added child component  
  7. import { ChildComponent } from './app.child.component';  
  8.   
  9. @NgModule({  
  10.   declarations: [  
  11.     APPComponent, ChildComponent  
  12.   ],  
  13.   imports: [  
  14.     BrowserModule,HttpModule  
  15.   ],  
  16.   
  17.   bootstrap: [APPComponent]  
  18. })  
  19. export class AppModule { }  

If everything is completed above then you can simply follow the below steps for running the application,

  • Step1: Open the node js command window and move to the location where you have added the application:
  • Step2: Excute ng serve command

If application runs successfully , the output should be,

Output

 

I hope you liked this -- please share it if you did. I will define the Angular service and send value from one component to another with the help of service in my later tutorial which is one of the main features in Angular applications.