@Output EventEmitter is a widely used technique to generate event from one component and listen to that event at another component. It is useful for reloading a data table at component from a different component.
Let’s take an example of having a list component where users are displayed. There is a new component to add / update users. Once someone adds / updates an user, a @Output EventEmitter is emitted from add / update component and that event is subscribed at list component where in the subscription the users list gets updated.
Step 1: Create a Child Component
It is assumed that you have already created an Angular application. Create a Child Component by running Angular CLI command ng generate child
In child.component.ts
add an @Output EventEmitter:
import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'], }) export class ChildComponent implements OnInit { @Output() myEvent: EventEmitter<string> = new EventEmitter<string>(); constructor() {} ngOnInit() {} generateEvent() { this.myEvent.emit('This Event is generated from Child Component'); // this is the line which emits event from child component and later listened at parent component } }
Step 2: Add template in Child to generate event
The next step is to add some code in child template to generate event explicitly. You can call the event emit code from somewhere else as well as per your requirement.
<button (click)="generateEvent()">Click to generate event</button>
Step 3: Listen to the event in Parent
The next step is to listen to the emitted event in the parent component.
<app-child (myEvent)="handleEvent($event)"></app-child>
Create a handleEvent
method in the parent component to handle the event.
handleEvent(msg) { alert(msg); }
That’s it. Once you click on the button at Child Component, it will throw an event to parent and the message will be displayed at parent component.
Here is a full working demo:-
Conclusion:
@Output EventEmitter is an Observable event emitter and listener technique through which we can communicate from child to parent.