Using @Output and EventEmitter

So, I have an event in one component and I want it to get handled in another component. Does Angular allow me to do that?

Big yes! In @angular/core, we have @Output and EventEmitter which allow us to emit event from one component to another.

Let us see how to do this.
So, to execute a function of parent component on the click of a button in child component, we use the decorator @Output

Say there is a button inside the child component and we create a variable index which is passed as the parameter of the event.

 

https://gist.github.com/NishuGoel/8923ef867180c59d2516babcc9d3681d

Here we have created a function food() which gets called on the click event of button and event foo is emitted. The parameter takes the value of index.
Now, using the child component inside the parent component like:

 

 

https://gist.github.com/NishuGoel/5f2183f21e592ac9dfc41f57fc595372

So this is how we could call the function in the parent component on the click event of the button placed in the child component.
Each time we click on the button, the index value is increased by 1.

Using @Output comes very handy when it comes to providing better user interaction.

Leave a comment

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