If you’re looking a way to communicate between Angular components I hope you’ll find your answer here.
In this article I’d like to show you how you can benefit from using @Output and EventEmitter in order to pass the data from child to parent component.
Let’s create new Angular app using Angular CLI.
Answer the routing and style questions and generate new project.
Now, let’s generate two components – ParentComponent and ChildComponent.
Passing data from child component
Let’s say we would like to pass the string value from the text input element in ChildComponent to the ParentComponent and display it.
So we add it in ChildComponent HTML template.
Now, we have to implement propagateChanges method. So take a look at the ChildComponent code.
As you can see @Output decorator is used here. The goal is to send data out of component along with EventEmitter using the events emitting mechanism.
Then we invoke emit method on textChanged and pass the text input string as a parameter inside of propagateChanges method. Pretty simple, right?
In order to receive the data in ParentComponent let’s go to the ParentComponent HTML template code.
As you can see we used ChildComponent template tag (app–child) with (textChanged) event listener. We’re passing $event value (in this case it contains input text value) into setInputText that we implement in ParentComponent in the next step.
As you can see setInputText method sets the value to inputText variable that will be displayed inside HTML paragraph element.
Let’s go live
Before running the project don’t forget to replace the auto-generated welcome page in app.component.html.
Okay, it’s time to run the app.
Browse to http://localhost:4200 and you should see the result.
And that’s it. I hope this tiny example will help you design data flow between components in your Angular app.