Child to parent communication in Angular is done by using @Output decorator and EventEmitter.
Child to parent interaction is happen by emitting an event to the parent.
To understand why we need to emit an event to a parent component read our article about Parent to Child communication.
The parent component doesn't have any business logic and it only contains the child component and it passes the input to a child. On completing the business logic, the child will emit an event to the Parent upon completion. The parent component contains nested child components and is used for data communication to the other components. The child components can contain reusable logic code. For example, a child component can contain a popup, dropdown etc.
Consider the parent component passes data to the child, the child forms a dropdown based on the parent data. The user selects a value from the dropdown and wants to emit the selected value to the parent. This can be done using @Output decorator and EventEmitter.
Parent Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'child-parent-interaction';
addresType: string;
addressChangeEventHandler($event: any) {
this.addresType = $event;
}
}
Create an event handler method addressChangeEventHandler() in AppComponent that captures the emitted data from ChildComponent.
Parent HTML
<div style="width:500px; height: auto; border: solid 2px #bce4f7; padding:20px;">
<h1>App Component</h1>
<h3>Ship to: {{addresType}} <ng-container *ngIf="addresType != null">Address</ng-container></h3>
<app-child (selectedAddress)="addressChangeEventHandler($event)"></app-child>
</div>
Child Component
import { Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
selectedAddressType: string;
constructor() { }
@Output() selectedAddress = new EventEmitter();
onAddressTypeChange() {
this.selectedAddress.emit(this.selectedAddressType);
}
}
In Child Component, Create an instance of EventEmitter and assign it to @Output decorator. selectedAddress will be the event emitted to the Parent component
Child HTML
<div style="border: solid 2px #bce4f7; height: auto; padding:10px">
<h2>Child Component</h2>
<h5>Choose Shipping Address Type</h5>
<select [(ngModel)]="selectedAddressType" (change)="onAddressTypeChange()">
<option value="Permanent">Permanent</option>
<option value="Temporary">Temporary</option>
</select>
</div>
Run the program and you will see the output as seen in the screenshot.