Introduction
While working on an Angular application we generally follow a practice where we bind our typescript code with our HTML template by means of multiple types of bindings. About these binding, we have already discussed in my last blog. But while working on a real organization-level application this is not the only thing that is required for the data flow. Most of the time we come across scenarios where we generally need to pass the data among the components. In this blog, we will be discussing the same.
Parent to Child component
In this section, we will be discussing the data transfer from a parent component to its child component. Let's do a simple activity to understand this.
I have created a simple angular application in which there is an app.component inside which I have used <app-student-header> a child component. Now I want to pass some data from this app.component to its child and show it in the marked area.
To do such types of operations, the Angular framework provides us @Input() decorator. This decorator tells the compiler that whatever value is coming from the parent with the identical name will initialize this property decorated with @Input() decorator. To get this done, first create a property with @Input() decorator inside the child component as shown in the picture and then use that property as an HTML property of the child component tag in the parent component's HTML.
And initialize that HTML property in the parent component with the desired value and that value will get displayed on UI in the child component.
Child to Parent
In the above section, we saw the value being passed from the Parent to Child component in the form of property, now we want something to be displayed in a parent being passed from the child. For transferring data from child to parent we need to generate a custom event and that event has to be used in the parent component. Let's understand this with another simple activity.
In your child component create a new property with @Output() decorator and initialize it with a new instance of EventEmitter. This testEmit will act as a custom event and will be emitted to the parent class. Now create a button in the HTML of the child component to emit this custom event and call a method to emit this event on its click.
In the parent component's HTML use this custom event just like other events and invoke a method.
This customEvent() method will have the definition in the typescript file of the parent component and this $event can be utilized to get the emitted value from the child component.
*I will come up with another blog sometime, in which we will be transferring data between the components when there is no relationship between the components.