Angular is based on a one-directional data flow and does not have two-way data binding. So, how do you get a component to emit an event to another component?
In Angular, a component can emit an event using @Output and EventEmitter. Both are parts of the @angular/core.
Confused by the jargon? Let’s simplify it together. Consider the AppChildComponent as listed below:
There is a button in the AppChildComponent template which is calling the function handleclick. Let’s use the app-child component inside the AppComponent as shown in the listing below:
Here we’re using AppChildCopmponent inside AppComponent, thereby creating a parent/child kind of relationship, in which AppComponent is the parent and AppChildComponent is the child. When we run the application with a button click, you’ll see this message in the browser console:
So far, it’s very simple to use event binding to get the button to call the function in the component. Now, let’s tweak the requirement a bit. What if you want to execute a function of AppComponent on the click event of a button inside AppChildComponent?
To do this, you will have to emit the button click event from AppChildComponent. Import EventEmitter and Output from @angular/core.
Here we are going to emit an event and pass a parameter to the event. Consider the code below:
Right now, we are performing the following tasks in the AppChildComponent class:
1. Created a variable called counter, which will be passed as the parameter of the emitted event.
2. Created an EventEmitter valueChange, which will be emitted to the parent component on the click event of the button.
3. Created a function named valueChanged(). This function is called on the click event of the button, and inside the function event valueChange is emitted.
4. While emitting valueChange event, value of counter is passed as parameter.