#
Receive data from a Child Component in Angular
This tutorial will explain to you how to receive data from the child component in Angular 4.
Creating a child component in Angular is the same thing as creating a component in Angular. All components you create are part of another component so, you can name them a "child component". But not all the components are "parent". If you place the X component into Y component, Y is the parent and X is the child.
For this example, you have to create a new application in Angular and create a child component into the Angular application.
In my example, app Component is the parent Component and child1 Component is the child Component.
Pay attention to the following files:
<!--This is app.component.html file -->
<div style="text-align:center">
<h1>
How to pass a variable from !
</h1>
<app-child1 (childevent)="getDataFromChild($event)"></app-child1>
<div class="parent"> <br> Parent variable: <br> </div>
</div>
/* This is app.component.css file */
.parent {
background-color: rgb(200, 227, 250);
}
/* This is child1.component.ts file */
import { Component, OnInit } from '@angular/core';
import { Output } from '@angular/core';
import { EventEmitter } from '@angular/core';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
@Output() childEvent: EventEmitter<string> = new EventEmitter<string>();
constructor() { }
ngOnInit() {
this.childEvent.emit("Data passed from Child Component");
}
}
<!--This is child1.component.html file -->
<div>
child1 works!
</div>
/* This is app.component.ts file */
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myText: string = 'Child to Parent Component !';
parentVariable: string;
getDataFromChild(event) {
this.parentVariable = event;
}
}
If you test the application in the browser, you will see:
What you have to retain is:
- in the parent view you have
(childEvent)="getDataFromChild($event)"
- the
childEvent
is defined in the child ts file - in the child Component the variable is defined by :
@Output() childEvent: EventEmitter<string> = new EventEmitter<string>();
- when you want to "send" the value to the parent component you have to "emit" the value:
this.childEvent.emit("Data passed from Child Component");