Tuesday, August 25, 2020

What are EventEmitters?

Angular applications are made using Components, most often we will have to arrange the components in a hierarchy (parent/child components). We will have to pass values from the parent to child components and from the child to parent component to make the App functional.

To pass values from a parent component to a child component we use the @Input property/decorator.
To pass values from a child component to a parent component we need to emit an event using @Output and EventEmitter. Both are parts of the @angular/core.

Custom events are EventEmitter instances. To create a custom event we need to create an instance of EventEmitter with an @Output decorator Then this instance calls emit() method to emit payload which can be received by event object $event.

EventEmitter declaration and emit from Child Component
                import { Output, EventEmitter } from '@angular/core';
                @Output() handleClickEvent = new EventEmitter();
                this.handleClickEvent.emit(<payload>);    

Output decorator binding in the parent component
                <app-child (handleClickEvent)='displayMessage($event)'></app-child>        
  
The displayMessage function will handle the click event from the Child component, it also received the <payload> from the child component as a parameter.

                displayMessage(strMessage) {
                                this.message = strMessage;
                }


Search Flipkart Products:
Flipkart.com

No comments: