Call child component method from parent class - Angular
In Angular, to share data from a child component to a parent component, the most common approach is using EventEmitter with @Output()
. Here's how it works step by step:
Steps for Child-to-Parent Data Sharing
- In the Child Component:
- You define an
EventEmitter
using the@Output()
decorator to emit the data.
- You define an
- In the Parent Component:
- The parent component listens for the event emitted by the child and handles the data that is sent.
Example:
1. Child Component (child.component.ts
)
Here, we want to send data (e.g., a message) from the child component to the parent.
typescript
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendData()">Send Data to Parent</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
// Step 1: Declare an EventEmitter and use @Output to make it available to the parent
@Output() messageEvent = new EventEmitter<string>();
// Method to emit the data to the parent component
sendData() {
const message = 'Hello Parent!';
this.messageEvent.emit(message); // Step 2: Emit the data
}
}
2. Parent Component (parent.component.ts
)
Here, the parent component listens for the event emitted by the child.
typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{ receivedMessage }}</p>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
receivedMessage: string;
// Step 3: Define a method to handle the event and receive data from the child
receiveMessage(message: string) {
this.receivedMessage = message;
}
}
Explanation:
Child Component:
- We define an
@Output()
propertymessageEvent
of typeEventEmitter<string>
, which emits data of type string. - When the button is clicked, the
sendData()
method is triggered, and the event emits the data (the string "Hello Parent!") to the parent component.
- We define an
Parent Component:
- The child component (
app-child
) is used in the parent’s template. - We bind the
messageEvent
of the child component to thereceiveMessage($event)
method in the parent. The$event
holds the data emitted by the child. - The
receivedMessage
property in the parent component is updated with the message from the child.
- The child component (
Key Points:
@Output()
: This decorator makes the event emitter available to the parent component.EventEmitter
: This is used to emit data or events from the child to the parent.- The parent listens for the event using Angular's event-binding syntax
(eventName)="handlerMethod($event)"
.
This approach allows you to share any type of data from the child to the parent in Angular.