Angular allows child components to communicate with parent components using @Output and EventEmitter. This enables the child to emit events and pass data back to the parent when something happens (for example, when a button is clicked).
@Output decorator exposes an event from the child component to the parent.EventEmitter is used to create and emit custom events with data.(messageEvent)="receiveMessage($event)".receiveMessage()) receives the emitted value via the special variable $event.@Output() messageEvent = new EventEmitter<string>();this.messageEvent.emit('Some value');<app-child (messageEvent)="receiveMessage($event)"></app-child>childMessage: string = '';) and a handler method receiveMessage(message: string) to store the incoming data.
// child.component.ts - emits a message to the parent
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: '<button (click)="sendMessage()">Send Message</button>',
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
}
// parent.component.ts - listens to the child's event
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Message from Child: {{ childMessage }}</p>
`,
})
export class ParentComponent {
childMessage: string = '';
receiveMessage(message: string) {
this.childMessage = message;
}
}
When the user clicks the Send Message button in ChildComponent, the method sendMessage() is called.
Inside sendMessage(), the child emits an event: this.messageEvent.emit('Hello from Child!');
The parent template is listening to this event using (messageEvent)="receiveMessage($event)". As soon as the child emits, receiveMessage() in ParentComponent runs and receives the value 'Hello from Child!'.
Finally, the parent stores that value in childMessage and displays it in the UI: Message from Child: Hello from Child!
childMessage = '';) to avoid undefined errors.$event to capture the emitted value in the parent template.userSelected, itemAdded) to make the intent clear.name and age) from the child to the parent and display its properties.@Input and @Output to allow two-way communication between parent and child, such as updating a form field from both sides.