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
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
<app-item-selector (itemSelected)="handleSelection($event)">
Last Selection: {{ lastSelectedItem }}
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).