Blog>
Snippets

@Output and Event Bubbling

Create an example of event bubbling with @Output, where a child component emits an event that is propagated to a higher-level parent component.
class ChildComponent {
  // Event emitter with @Output decorator
  @Output() childEvent = new EventEmitter<string>();

  // Function to emit an event
  emitEvent() {
    this.childEvent.emit('Data from child');
  }
}
This piece of code represents a child component that has an event emitter defined with the @Output decorator. It can emit an event carrying a string to the parent component.
class ParentComponent {
  // Function to handle the event emitted from the child
  onChildEvent(data: string) {
    console.log('Received from child:', data);
  }
}
This code snippet represents the parent component with a function designed to handle events from the child component.
<!-- Parent component template -->
<child-component (childEvent)="onChildEvent($event)"></child-component>
This is the HTML template of the parent component. It listens for the 'childEvent' emitted by the child component and calls the 'onChildEvent' method upon capturing that event.