Sharing data between components in Angular is one of the most important part to understand. We are going to learn how to pass data from one component to another component using
EventEmitter in Angular app.
Let’s discuss different methods of sharing data in any angular application. We will focus on these methods:
@Input: sharing data from parent to child
@ViewChild: sharing data from child to parent
@Output & EventEmitter: sharing data from child to parent
Method 1: Parent to Child using
This is the most common method of sharing data in Angular application. We will use @Input() decorator to pass data. Create a parent component named
app-parent in your app folder. Use this command to generate the component:
Creating parent component
ng g c parent
Now, let’s create child component named
app-child using this command in your app folder.
Creating child component
ng g c child
Till now, we have just created our parent and child components in our app. Let’ see how to pass data between them. Import the
Input decorator in line 1 of
appChildMessage property with
@Input() decorator in same file.
Add this line to
Now, let’s add these lines to parent component.
So, the complete code would be like this.
Method 2: Child to Parent using
Using @ViewChild() decorator, we can inject one component to another, giving the parent access to its attributes and functions.
Note: Child won’t be available until after the view has been initialized. So, we need to implement the AfterViewInit lifecycle hook to receive the data from the child.
Let’s look at our parent component code. Write these lines in parent component.
AfterViewInit in component class.
Add these lines in component class file.
Let’s look at complete code.
Method 3: Child to Parent using
In this method, child component will emit the data, which will be listen by parent component. This ideal condition for this approach is when you want to share some data on some events like button clicks, users and other form related events.
Use this link to read more about @Output and EventEmitter.
We are going to create a function in the parent to receive the message and set it equal to the message variable. Also, we are going to declare a
messageEvent variable with the
Output decorator and set it equal to a new event emitter. Then we will have a function named
sendMessage that calls emit on this event with the message we want to send. At the end, we will create a button to trigger this function.
Let’s look at complete code.
In our post, we have learned about how to share data between parent and child components using @Input(), @Output and EventEmitter. Data sharing is very important concept, and everybody needs to share data between application’s components.
- Fresh releases of Visual Studio 2017 for Mac and TypeScript 3.2
- Learn Functions In TypeScript
- Update Angular 6 to Angular 7 version
- What’s new in Angular 7.0
- What is GraphQL? An Inside look at GraphQL