We all know that angular is a component based framework that is used to develop single page application. We divide a page into small chunks of components then combine it together to make a page. So it becomes vital to handle components efficently and established a communication between them.
There are many ways to share data between the components but the most common and straightforword method is by using @Input() and @Output() decorators.
So, in this blog i will show you how input and output decorators shares the data between components.
1. Parent to Child : sharing data via @input () .
2. Child to Carent : sharing data Via @output () and EventEmitter
@input decorator marks the property as the input property means it can recieve the data from parent component. By using property binding, parent component bind it to a component property and whenever the the value changes, angular updates the vaulue in the child components.
Below is the illustration:-
when we declare a variable wtith th input decorator in the child component it allows that variable to be recieved from the parent component template. In this scenario, we define a message variable in the parent and use square brackets to send the data to the child.
Now the child component can display the data in its own template.
@Output() decorates the property as the output property. We intialize it as an EventEmitter. The child coponent raises the event and passes the data. The parent component listens to events using event binding and reads the data.
Another option to communicate info is for the child to emit it so that the parent may listen in. This technique is great for sharing data changes caused by button clicks, form entries, and other user actions.
In the child we declare a message of that variable with the output decorator and set it equal to a new event emitter.
Then we create a funtion named send message that calls emit on this event with the message we want to send. Lastly we create a button to trigger this funtion in the HTML .
In the parent we ceate a funtion to recieve the message and set it equal to the message variable.The parent can now subscribe to this message event that’s outputted by the child component then run the recieve message funtion whenever that event occours.