Hello everywhere, in this article we will see the basic use case of @Ouput and EventEmitter in Angular 8. In order to notify or pass some information to a parent component about any event in its child components we use the Output decorator along with the EventEmitter to raise a custom event.
The child component in this case becomes a publisher of the event while the parent component subscribes to it. Let us create a simple app with two components parent & child and handle the keyup event raised on the child component and pass on the data to the parent.
Here we have a simple text box and a method named onKeyPressed to handle the keyup event on it. This function will take in the current text of textbox as a parameter.
- We need to first import Output and EventEmitter from @angular/core
- Then we create a new EventEmitter object named keyPressOnChild and decorate it with @Output
- Then in the logic for keyPressedEvent we use the emit property of keyPressOnChild to publish the event and pass on the required parameter.
Also Read: Upload Files and Images in Angular
- So, basically an Event named keyPressOnChild is now published by the child component and the parent can subscribe.
- While adding the selector for the child component, the parent can subscribe to its custom event by providing a event handler method (similar to default events like submit, keyup etc.)
- Here we will create a variable and assign the value passed from the child component to it.
- We then just display this value on screen through the parent component html file
That’s it!! We have implemented @output and EventEmitters to fulfill one of the most common requirement of an angular app, i.e. component communication.