What is Output Decorator in Angular: Explanation and Example
@Output decorator in Angular marks a property in a child component as an event emitter that can send data to its parent component. It allows the child to communicate by emitting custom events that the parent can listen to and respond.How It Works
Imagine you have a child component inside a parent component, like a button inside a form. The child needs a way to tell the parent when something happens, such as a button click. The @Output decorator helps by turning a property in the child into an event that the parent can listen to.
Technically, @Output decorates a property that is an EventEmitter. When the child component calls emit() on this property, it sends a signal with optional data to the parent. The parent listens to this event using Angular's event binding syntax, like (eventName), and runs a function when the event occurs.
This setup is like a walkie-talkie: the child component 'talks' by emitting events, and the parent 'listens' and reacts accordingly. This keeps components loosely connected and easy to manage.
Example
This example shows a child component emitting a message to its parent when a button is clicked.
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!'); } } @Component({ selector: 'app-parent', template: ` <app-child (messageEvent)="receiveMessage($event)"></app-child> <p>Message: {{ message }}</p> ` }) export class ParentComponent { message = ''; receiveMessage(msg: string) { this.message = msg; } }
When to Use
Use the @Output decorator when you want a child component to send information or signals to its parent. This is common in user interfaces where child components handle user actions like clicks, selections, or form inputs.
For example, a custom dropdown component can emit the selected value to the parent, or a modal dialog can notify the parent when it closes. This pattern helps keep components independent and reusable while enabling clear communication.
Key Points
- @Output marks a property as an event emitter from child to parent.
- It uses
EventEmitterto send events with optional data. - Parents listen to these events with Angular event binding syntax.
- It enables clean communication between components without tight coupling.