Passing Data to Parent Component in Angular
It is possible to pass data from a child component to a parent component. This is done by emitting events using a special object EventEmitter and a method emit. The child component will emit events, passing along some data with the event, and the parent component will catch the events, receiving data from the parent component.
Let's try it in practice. To do this, we need to do a number of steps. First, we import the @Output decorator and the EventEmitter class into our child component:
import { Component, Output, EventEmitter } from '@angular/core';
Now in the child class we will create a property onData, the value of which will be a new object EventEmitter, containing the string:
export class UserComponent {
@Output()
public onData = new EventEmitter<string>();
}
Now let's create a method send, the call to which will emit an event onData to the parent component with the given text:
export class UserComponent {
@Output()
public onData = new EventEmitter<string>();
send() {
this.onData.emit('xxx');
}
}
In the child component template, we will make a button that, when clicked, will call the send method:
<button (click)="send()">
send data
</button>
In the parent component, we will create a method onData, which will be automatically called when the corresponding event is emitted from the child component. The passed data will be put into the method parameter:
export class AppComponent {
public onData(data: string) {
console.log(data);
}
}
In the parent component template, we bind an event to the child component tag:
<app-user (onData)="onData($event)"></app-user>
In the child component, make three buttons that emit different events. Catch the emitted events in the parent component.