Angular - How To Pass Value From Child To Parent

Passing values from one page to another is a very common and necessary task in most application development, however, we need some mechanism in Angular also to do the same.

Angular has provided various ways to do so but here, we will use the @ViewChild directive provided by Angular.

Let's start.

  1. Create a component and name it as child.

    Use this command - ng g c child

    This will create a child component in your app folder.

  2. Copy the below code and paste it in the child.component.ts file.
    1. import {  
    2.     Component,  
    3.     OnInit  
    4. } from '@angular/core';  
    5. @Component({  
    6.     selector: 'app-child',  
    7.     templateUrl: './child.component.html',  
    8.     styleUrls: ['./child.component.css']  
    9. })  
    10. exportclassChildComponent {  
    11.     message: string = "Hola Ankit!"  
    12.     constructor() {}  
    13. }  
  3. Here, we have defined one property message and we are assigning it to some dummy data. We will use this property in the Parent component.

  4. Create another component and name it as parent.

  5. Copy the below code and paste it in your parent.component.ts file.
    1. import {  
    2.     Component,  
    3.     AfterContentInit  
    4. } from '@angular/core';  
    5. import {  
    6.     ChildComponent  
    7. } from '../child/child.component';  
    8. @Component({  
    9.     selector: 'app-parent',  
    10.     template: `  
    11. Message: {{message}}  
    12. <app-child></app-child>  
    13. `,  
    14.     styleUrls: ['./parent.component.css']  
    15. })  
    16. exportclassParentComponentimplementsAfterContentInit {  
    17.     @ViewChild(ChildComponent) child;  
    18.     message: string;  
    19.     constructor() {}  
    20.     ngAfterContentInit() {  
    21.         debugger;  
    22.         this.message = this.child.message  
    23.     }  
  6. Here, we have used @ViewChild directive to get the child component property. Also, we have implemented AfterContentInit Lifecycle hook to render the child property on the browser.

  7. We have also set the child property to parent page property message inside ngAfterContentInit and then bound the same property to the template using interpolation {{}}.

  8. Now, run the application using ng serve and open the parent component in the browser. You will observe that the "Hola Ankit" text will be rendered on screen.

    Img_3

Hope this article will help people to understand how to pass a value from child to parent component.