Angular, Software Development

Angular EventEmitter Child to Parent Component

This post shows how to pass data from the child component to the parent component using Angular EventEmitter. We have migrated the codes from Angular 7.20 to 15.0.0.

Angular Requirements

We used the following items for this post.

  • Angular CLI 15.0.4
  • NPM 8.19.2
  • Node 18.12.1
  • Internet connection

Pass Data From Parent to Child Component in Angular

We previously showed how we could pass data from a parent to a child component using the @Input directive. The sample codes show the typical flow of information when we have a hierarchy of Angular components. However, sometimes, we need to pass data back to the parent component from the child component. For instance, we may have a form that accepts text input from a user. Whenever he supplies text, we send that data to the parent component.

In this post, we have codes that use the Angular EventEmitter to send data from a child to a parent component. Also, we use the @Output directive in the parent component to work with events coming from an EventEmitter.

Angular EventEmitter In The Child Component

Before going to the nitty-gritty of the implementation, let’s see what the child component has first. It has simple HTML codes that display a textbox and a button. When a user types in any text and clicks the Add button, the codes trigger a call to a JavaScript function.

Consider the following code snippet.

The TypeScript function’s main task is to emit the text data and clear the textbox for the next input data.

Also, we have the following line of codes for the parent component. More about that a bit later.

All in all, we have the following complete TypeScript codes for the child component.

Note that this technique may not be a robust solution, especially for Angular projects with many components that are not necessarily in a hierarchy. Meaning these Angular projects don’t solely rely on using components’ selectors. Most of them display components in a modal dialog.

Just bear that in mind. Also, please don’t overuse this technique. Sometimes, we are better off using Rxjs (or something similar).

Angular EventEmitter Calls a Function in Parent Component

Okay, now we are on the parent component side. We use the child component in the parent component by using its HTML selector.

Notice the itemNameFromChild property that we annotated with @Output? That property is the Angular EventEmitter that will trigger the onAddItem function in the parent component. Zooming in on the HTML codes, we have the following.

We will have the following video demo when we run the Angular application.

Download the Angular EventEmitter Sample Codes

We have migrated the codes to Angular 15. Please check the codes out on our GitHub account.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like