Angular - Interaction Methods for Components.

Sharing data is a key concept to understand before plunging into your first Angular Project. I offer four different methods for sharing data between Angular components in this blog.

1) Sharing Data from Parent to Child:  @Input

@Input decorator is an Angular decorator that can be used to transfer data from Parent to Child. In an Angular application, this is one of the most common ways to share data from parent to child. Let's take a look at how the @Input decorator works in the following snippets.

# parent.component.ts


# child.component.ts


2) Sharing Data from Child to Parent:  @ViewChild

This @ViewChild() decorator is provided by Angular and can be used to insert one part into another. This is now possible thanks to the parent's access to the child's characteristics and functions. It's also worth noting that the Child part is only available after the view has been initialised. To get the data from the kid, we must use the AfterViewInit lifecycle hook. In the following snippets, we'll see how the @ViewChild decorator works.

# parent.component.ts



# child.component.ts


3) Sharing Data from Child to Parent:  @Output & EventEmitter 

The @Output decorator adds configuration metadata to a class field and allows it to be marked as an output property. 
The data will be emitted by the child component and retrieved by the parent component. To begin, if data must be sent from the child to the parent, the data must first be emitted from the child. To make it work, we'll need to add a function to the parent that receives the message and sets it equal to the message's variable. The @Output decorator now allows the child to declare a message event attribute. As a result, the parent component will now subscribe to the message event that the child component emits and execute the receive message function whenever it occurs.

# parent.component.ts


# child.component.ts




4) 
Sharing Data Between Various Components: 

A service is a class that holds data or functions based on the needs of the application and also stores the logic in the file, allowing us to reuse the code with different components as required.

# data.service.ts


# parent.component.ts


# sibling.component.ts




Conclusion:-

In this blog, you'll learn how to use @Input(), @Output(), and EventEmitter to share data between parent and child components, as well as how to share data between different components. Data sharing is a crucial idea because everybody needs data to be shared between application components. I hope you found this description of the data sharing concept in Angular useful. 

Comments