In our previous blog post we discussed passing data from the parent component to a child component. In this blog post we will discuss passing data from the child component to a parent component.
Child Component
child.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent {
@Output() childDate: EventEmitter<string> = new EventEmitter();
sendDate() {
this.childDate.emit(new Date().toDateString());
}
}
In the child component, we need to import Output
and EventEmitter
in order to send the data to the parent component. We then create a method called sendDate
which will contain the class variable childDate
which is of type EventEmitter
in order to send the date to the parent component.
child.component.html
<button (click)="sendDate()">Send Date</button>
We create a button in the child component in order to call the method sendDate
and send the date to the parent component.
Parent Component
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
public todaysDate: string;
receiveDate($event: any) {
this.todaysDate = $event;
}
}
In the parent component we create a class variable todaysDate
and a method receiveDate
which will be used to save the data sent by the child component to the class component todaysDate
.
parent.component.html
<app-child (childDate)="receiveDate($event)"></app-child>
<h3>Child Component</h3>
{{todaysDate}}
In the view of the parent component, we then add child component’s selector along with the childDate
variable from the child component and wrap it in the round brackets which is used for events and pass on the data from the child component to the receiveDate
method in the parent component with the parameter $event
.
app.component.html
<app-parent></app-parent>
We use the root component in order to insert the parent component’s selector and display its contents.
NOTE: We are only using app.component.html
since it is a simple example. It is not necessary to always use app.component.html
.
Once we click on the Send Date
button, we get the following: