In this blog, I will discuss how to communicate between components in Angular using @input and @output life cycle hooks, property, and event binding.
Communicating with child component
First, we will see how to transfer data from a parent component to a child component. This is probably the most common method of data sharing from parent to child component. It works by using @input life cycle hook and property binding. So let’s get started.
Initially, declare a variable in child component with the decorator @input. As shown below:
Note: Input class must be imported from angular core
Data type of input can be anything i.e. a string, a number, or an object. I used any to make it more generic.
In Child.component.html show dynamic Contact Name through interpolation:
In parent component, declare an object with contact information:
Then, bind the value of name of the contact object it with contactName property of child component:
Below are the results in the browser:
By following the above process, you can transfer data from a parent component to any child component in Angular.
Communication with Parent Component
We have now seen how to send data into a child-component. In this process, we will cover how to pass data back to parent component from child component below.
Initially, declare an event with @output decorator in child component as shown below:
Note: EventEmitter and Input class must be imported from Angular Core library.
Add a button in the child component html to trigger this event:
Now, we will have parent component listen to that child event. For this, add another event handler to the child component element:
Define the function in parent component which will listen to the event. I have declared a string variable in the parent component which text will change on click event in child and data will update with what will be pass from child component:
In this blog, we have learned how to pass data from parent to child component and vice-versa in Angular using @input and @output life cycle hooks and Property and Event Binding.
For any questions, please comment below. I will be pleased to assist more.