How to share data between child and parent component using events in Angular

If you are new to Angular and learning about event emitters, you have come to the right place. As stated in the official Angular documentation, “ EventEmitter — use by directives and components to emit custom Events”.

Let’s learn how different components can communicate in Angular using a basic example of a To-Do List App. This web application will have three components:

  • App component
  • Add Task component
  • List of Tasks component

App will provide an input field and a button in Add Task. When user inputs task name and clicks “Add Task” , the newly added task will be added to the To-Do List.

Since we have three separate components, these should be able to communicate and share data, for the functionality to work. Angular Event Emitters makes this communication possible.

First, using @Output decorator, emit an event from Add Task when user clicks ‘Add Task’ button containing the task value entered by user. Use below code in your Typescript file.

// variable to store user input
taskName;
// Output decorator that enables values flow out of the component
@Output() taskNameEvent = new EventEmitter<string>();
// this function is called when user clicks Add Task button
addTask() {
// emit custom event
this.taskNameEvent.emit(this.taskName);
}

Now you have to subscribe to this event and fetch the value that is being passed.

Go to HTML template file for App Component (app.component.html) and subscribe to this event.

// notice the taskNameEvent is the event emitted by add task component
<app-add-task (taskNameEvent) = 'getTasks($event)'></app-add-task>
// getTasks can be replaced with any name of your choice

Define the getTask() function in app component typescript file to fetch data from the event.

//array of task names
taskName: string[] = [];
//get the value from event and add to array
getTasks(tName: string) {
this.taskName.push(tName);
}

All set! You can now access this data from List of Tasks component by using @Input decorator.

//
// since data is in the form of an array, use *ngFor to iterate
//using property binding display taskListVal
<app-list-of-tasks *ngFor="let task of taskName" [taskListVal]= 'task'>

Finished App will look something like this. You can always add custom styles and additional features like adding close button on each task to remove it on completion.

📁Source code available here.

To-Do-List is live and running at Heroku 🔥

I’m a software engineer. I love programming and teaching CS and Maths.