How To Pass Value From Parent To Child Component

During development, we normally face situations where we need to pass the value from one component to another. Angular has provided various ways to pass such values.

Here, we are considering a scenario where we call one component inside another component,  hence I have named them child and parent component.

So let's start developing the component.

  1. Create a component and name it as hero-child component.

    use command - ng g c hero-child

  2. Copy the following code and paste in your hero-child.component.ts.
    1. import {  
    2.     Component,  
    3.     OnInit,  
    4.     Input  
    5. } from '@angular/core';  
    6. @Component({  
    7.     selector: 'app-hero-child',  
    8.     template: `<p>{{masterName}}</p>`,  
    9.     styleUrls: ['./hero-child.component.css']  
    10. })  
    11. exportclassHeroChildComponent {  
    12.     @Input('childValue') masterName: string;  
    13.     constructor() {}  
    14. }  
  3. Here, we have defined @Input and imported it from @angular/core. Inside inputdirective we have defined one property, 'childValue,' whose value will be set by the parent component or the component which will use hero-child component as a child component. 

  4. We have also defined 'masterName' which is used to access the value set to 'childValue' via @Input.

  5. Create another component and name it as hero-parent component. Just use the command - 
    ng g c hero-parent
    1. import {  
    2.     Component,  
    3.     OnInit  
    4. } from '@angular/core';  
    5. @Component({  
    6.     selector: 'app-hero-parent',  
    7.     template: `  
    8. <h2>{{masters}}</h2>  
    9. <app-hero-child [childValue]="masters">  
    10. </app-hero-child>  
    11. `,  
    12.     styleUrls: ['./hero-parent.component.css']  
    13. })  
    14. exportclassHeroParentComponent {  
    15.     masters = 'Master'  
    16. }  
  6. Here, we have invoked hero-child using its selector inside the template of hero-parent.

  7. We have also created a property named 'masters' and bound it to child component property [childValue] which we have defined inside @Input tag in child component.

  8. We have also bound the master's value in template <h2> tag using interpolation.

  9. Now, if you run the application and browse the hero-parent component, you will see master value rendered two times on the browser -- one inside <h2> tag and one via child component childValue property.

    How to pass value from Parent to Child component