Using Angular’s EventEmitter to Share Data Between Child and Parent Components
Home
About
Articles
There are often scenarios in Angular where we need to communicate between components, specifically to send data from a child component to it’s parent component. Consider this Angular 12 app for managing a to do list:
When saving a new to do to the list, I’m using the child component (the dialog window) to send the new to do to an API to be stored in a database. In addition to this, I need to communicate to the parent component (the to do list) that the new to do was saved and add it to the list:
I’ll begin by demonstrating the current Angular app (currently without an EventEmitter) and explain how we can implement an EventEmitter to send data between the child and parent components.
In app.component.ts (the parent component) I’m retrieving the list of to dos from an API and assigning them to an array:
In app.component.html I’m looping through the array of to dos and referencing SaveNewToDoComponent (the child component) that is being used as a dialog window to save a new to do:
In save-new-to-do.ts (the child component) I’m retrieving the new to do from the form and sending it to an API to be stored in a database:
I’ll add an EventEmitter by adding an output decorator to the SaveNewToDoComponent class:
Also in the SaveNewToDoComponent class, I’ll emit an event containing the new to do once the to do has been sent to the API:
Below is the entire component save-new-to-do.ts using an EventEmitter:
Within app.component.html , I’ll use event binding to communicate the event occurring in the child component and send the new to do to the parent component by executing the new method ‘appendToDo’ , passing in the new to do as a parameter:
Finally, I’ll add the new method ‘appendToDo’ to the parent component to push the new to do to the array:
Now that I’ve added an EventEmitter into the Angular app, the list will be automatically updated with the new to do:
Thank you for reading this article! The full solution used in this guide is available at github.com/stevenmclintock/angular-event-emitter-example .
In Angular there are two different types of forms for a user to input data: reactive and template-driven. I personally prefer using reactive forms as they seem to follow the separation of concerns principle, where the core functionality is in the component and the presentation layer is stored in ... Read more
If you’re interested in building a caching service for Angular that will store the observable for a HTTP call in cache, there is an excellent article by Yury Katkov that will explain exactly how to do this using RxJS. Read more
Have you ever looked for a piece of HTML in the code of an Angular app and found something similar to <ng-container *ngTemplateOutlet=”navBarTemplate”></ng-container> instead? Read more
RSS