Blog>
Snippets

Using @Output to emit events

Show how a child component can use @Output and EventEmitter to emit custom events to its parent component.
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
  // Create an instance of EventEmitter
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    // Emit a custom event with data
    this.messageEvent.emit('Hello from the child component!');
  }
}
This piece of code defines a ChildComponent with a button in its template. When the button is clicked, the sendMessage() method is called, which emits a custom event named 'messageEvent' with a payload/message using Angular's EventEmitter.
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `<app-child (messageEvent)="receiveMessage($event)"></app-child>
            <p>{{ message }}</p>`
})
export class ParentComponent {
  message: string;

  receiveMessage(event) {
    // Handle the event triggered by the child component
    this.message = event;
  }
}
This snippet illustrates a ParentComponent including the ChildComponent in its template. It listens for the 'messageEvent' emitted by the ChildComponent and calls the receiveMessage() method to handle it. The received data (message) is then stored in a property called 'message' and displayed in the template.