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.
- 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.
- Copy the below code and paste it in the child.component.ts file.
- import {
- Component,
- OnInit
- } from '@angular/core';
- @Component({
- selector: 'app-child',
- templateUrl: './child.component.html',
- styleUrls: ['./child.component.css']
- })
- exportclassChildComponent {
- message: string = "Hola Ankit!"
- constructor() {}
- }
- 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.
- Create another component and name it as parent.
- Copy the below code and paste it in your parent.component.ts file.
- import {
- Component,
- AfterContentInit
- } from '@angular/core';
- import {
- ChildComponent
- } from '../child/child.component';
- @Component({
- selector: 'app-parent',
- template: `
- Message: {{message}}
- <app-child></app-child>
- `,
- styleUrls: ['./parent.component.css']
- })
- exportclassParentComponentimplementsAfterContentInit {
- @ViewChild(ChildComponent) child;
- message: string;
- constructor() {}
- ngAfterContentInit() {
- debugger;
- this.message = this.child.message
- }
- }
- 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.
- 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 {{}}.
- 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.
Hope this article will help people to understand how to pass a value from child to parent component.