Data sharing between components is an essential knowledge that everyone should have before starting their first Angular application. In this article, I’m going to discuss 3common methods that we can use to share data between Angular components.
- Sharing Data via Input
- Sharing Data via Output and EventEmitter
- Sharing Data with a Service
Sharing Data via Input
With the use of @Input() decorator, we can easily pass data from Parent component to Child component.
Sharing Data via Output and EventEmitter
Another commonly used way to share data is by emitting data from Child to Parent. With this approach, it is easy to pass data by events such as button clicks. In the parent component, we have to create a method to receive the messages and in the child component, we declare a messageEvent variable with the @Output() decorator and set it equal to a new event emitter. After that, we can create a method to emit data and trigger it on a button click.
Sharing Data via Service
Both the above-mentioned methods can only be used when there is a direct connection between the components such as parent-child. But with a shared service, we can share data between unrelated components(or sibling components).
In addition to 2 components, we need to create a new service file in this approach. In the service file, we need to create a private BehaviorSubject to hold the current value of the message and a variable to handle data as an observable. This variable will be used in the components later. Finally, we need to define a method to call on the BehaviorSubject to change its value.
In all other components(Parent, Siblings)First, we need to inject Shared Service in the constructor and then subscribe to the observable variable we created in the shared service. Then we can set that value to a local variable. Finally, If we change the value of the local variable in any of these components new value will be automatically sent to all other components.
These are only 3 very common approaches that we can use to share data between angular components and there are other approaches like ViewChild as well. Let’s discuss more topics regarding Angular in upcoming articles. Until then, HAPPY CODING!!.