To pass data from Child to Parent component in Angular, you typically use EventEmitter with @Output(). This allows the child component to send data to the parent component through an event.
Here’s how to implement this scenario:
1. Pass Data from Child to Parent Component
To pass data from the child to the parent component:
- Parent Component listens for an event emitted by the Child Component.
- Child Component emits an event to send data to the Parent Component.
Example: Pass Data from Child to Parent
Parent Component (TS)
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent {
public parentData: string = ''; // Property to hold data from child
// Method to handle the data coming from child
handleChildData(data: string): void {
this.parentData = data; // Update the parent data
}
}
Parent Component (HTML)
<h1>Parent Component</h1>
<p>Data from Child: {{ parentData }}</p>
<app-child (childEvent)="handleChildData($event)"></app-child> <!-- Listening to childEvent from child -->
Child Component (TS)
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent {
@Output() childEvent: EventEmitter<string> = new EventEmitter<string>(); // Declare event
sendDataToParent(): void {
this.childEvent.emit('Hello from Child!'); // Emit data to parent
}
}
Child Component (HTML)
<h2>Child Component</h2>
<button (click)="sendDataToParent()">Send Data to Parent</button> <!-- Trigger sendDataToParent when clicked -->
Key Points:
@Output()
: This decorator is used in the child component to create an event that can be emitted.EventEmitter
: A class used to emit events from the child component.- Event Binding (
(childEvent)
): The parent listens for the emitted event using event binding in the template. It handles the event by calling a method in the parent component. - Sending Data: When the child component emits the event using
this.childEvent.emit()
, the parent component receives the data through the handler method (handleChildData
).
Full Example Overview:
- Parent Component listens for the event
childEvent
emitted from the Child Component. - Child Component triggers the
sendDataToParent()
method that emits data to the parent.
This is a simple way to send data from child to parent in Angular using EventEmitter and @Output().