Angular — Sharing Data between components
Angular is popular framework for developing Single page web application. I am here explain you to how you can share data between components. But before that we need to understand types of relationship between components
Types of relationship between components
- Parent to child relationship
- Child to parent relationship
- sibling relationship
- No relationship between components
Parent to child relationship -
In parent to child relationship is one of the most common and straightforward way of sharing data. It works by using the @Input()
decorator to allow data to be passed via the template.
Here is Example of parent to child data sharing using @Input() decorator.
Parent to child communication demo
Child to parent relationship —
When we need to share data from child to parent we will have to use the ViewChild() decorator to get reference of the child component and get data from child to parent. One thing here is you can get data from child to parent after child view is initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.
Sibling relationship —
sibling component can share data between using combination of above two child to parent and parent to child relationship. Child1 send data to the Parent component and then parent send data to Child2 component
No relationship between components —
When there is no relationship between components that time you need to use Service to share data between
Here is an example.
I feel that we should use async pipe as much as possible, because of the subscription clean up feature. Then you don’t need the unsubscribe in ngOnDestroy.
Thank you for your valuable suggestion. I have updated the solution on stackblitz.
You can even use it in
*ngIf
if you want to check if the BehaviorSubject contains any value.Very useful tutorial to share data in angular … specially I like stackbiz links so any one can hands on with live example