In Angular app development, We all come across a situation to share data and information with another component. A component can share data to each other in various ways, these are:
As I have already created a demo over this platform to share data from parent component to the child component. Today we will create a demo to share data from child component to parent component. n the image at top, you can understand the data flow.
Let's have a look in the child component:
In the above file, We have created a counter variable, which we will pass as the parameter of the emmited event. After that created and Event Emmiter newValue, which will be emmited to the parent component on the click event of the button. And created a function name changedValue which is called on the event of the button, and within which event newValue is emitted. At last while emitting value newValue event, value of counter is passed as parameter.
In the parent component app component, the child component child Component can be used as shown in the shown below in parent component ts file
In the parent component, we are using <app-appchild> template with event binding to use the newValue event. Then we are calliing the displayVal function on the newValue event. At last, In the displayVal function, printing the value passed from the child component.
Right now, we are performing the following tasks in the AppComponent class:
Now the function of AppComponent is called on the click event of the button from the AppChildComponent. This is can be done with @Output and EventEmitter. When we run the application and click the button, we can see the value of the counter in the browser console. Each time we click on the button, the counter value is increased by 1.
In this article, we learned to create demo how to communicate from a child component to a parent component. We also saw the use of eventEmmiter in nodejs app. In further demos, we will explore other types of component communication.
That’s all for now. Thank you for reading and I hope this post will be very helpful for communcating data from child component to parent component.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.