Loading...

@Output in Angular

In Angular, @Output is a decorator that allows a child component to communicate with its parent component. It's used to emit events from the child to the parent, enabling data to flow upwards in the component hierarchy.

How @Output Works

When you use @Output in a child component, you're essentially creating an event that the parent component can listen to. The child component then uses an EventEmitter to emit the event, and the parent component handles the event in its template.

Example

Let's create a simple example with a parent component and a child component that uses @Output.

Child Component (child.component.ts)


    import { Component, Output, EventEmitter } from '@angular/core';
           @Component({
               selector: 'app-child',
    template: '<button(click) = "sendMessage()"> Send Message to Parent</button>'   
           })
    export class ChildComponent {
                @Output() messageEvent = new EventEmitter<string>();
      sendMessage() {
        this.messageEvent.emit('Hello from child!');
      }
    }
    

Explanation:

  • @Output() messageEvent = new EventEmitter<string>();: Declares an output property messageEvent that emits a string value. EventEmitter is used to create the event.
  • sendMessage(): This function is called when the button is clicked. It uses this.messageEvent.emit() to send the message to the parent component.

Parent Component (parent.component.ts)


    import { Component } from '@angular/core';
    @Component({
      selector: 'app-parent',
      template: '<app-child>(messageEvent)="receiveMessage($event)" ></app-child>
                        <p>Message from child: { { receivedMessage } }</p>'
                        })
    export class ParentComponent {
      receivedMessage: string;
      receiveMessage(message: string) {
        this.receivedMessage = message;
      }
    }
    

Explanation:

  • <app-child (messageEvent)="receiveMessage($event)"></app-child>: Listens for the messageEvent emitted by the child component and calls the receiveMessage() function. $event contains the data emitted by the child.
  • receiveMessage(message: string): This function receives the message from the child and stores it in the receivedMessage property.
  • {{ receivedMessage }}: Displays the received message in the template.

Key Points

  • @Output allows data to flow from child to parent components.
  • EventEmitter is used to create and emit events.
  • $event in the parent template contains the data emitted by the child.
  • You can emit any type of data (string, number, object, etc.).

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!