How to use @Output EventEmitter in Angular

@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.tsadd an @Output EventEmitter:

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.

Step 3: Listen to the event in Parent

The next step is to listen to the emitted event in the parent component.

Create a handleEventmethod in the parent component to handle the event.

 

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.

Leave a Reply

Your email address will not be published. Required fields are marked *