66. Component Interaction: Output and EventEmitter
To communicate data up the component tree (from Child to Parent), Angular uses the @Output() decorator combined with the EventEmitter class.
1. Defining the Output in the Child Component
An @Output() property must be an instance of EventEmitter<T>, where T is the type of data to be sent. The EventEmitter provides the emit() method.
typescript // item-selector.component.ts (The Child) import { Component, Output, EventEmitter } from '@angular/core';
@Component({ /* ... */ }) export class ItemSelectorComponent {
// Define the event name and the type of payload (string in this case) @Output() itemSelected = new EventEmitter<string>();
selectItem(itemName: string) { // 1. Trigger the event this.itemSelected.emit(itemName); } }
2. Listening to the Event in the Parent Component
The parent component listens using event binding syntax (( )) and maps the emitted value (which Angular provides via the $event keyword) to a parent method.
typescript // parent.component.ts export class ParentComponent { lastSelectedItem: string = 'None';
// Method to handle the event payload
handleSelection(name: string) {
this.lastSelectedItem = name;
console.log(Child selected: ${name});
}
}
html
<!-- parent.component.html --> <!-- When (itemSelected) fires, execute handleSelection, passing the emitted payload ($event) --><app-item-selector (itemSelected)="handleSelection($event)"> </app-item-selector>
<p>Last Selection: {{ lastSelectedItem }}</p>Best Practice: Always define the output event name clearly and use EventEmitter only for component communication, not for services (where RxJS Subjects should be used).