eatthecode.com

Angular Share Data Between Components

Angular share data between components details

Definitions and illustration

In angular, sharing data between components may cause headache for many of developers, specially in case you need to handle large scale application. In this post, I will introduce the different ways of handling shared data between components. Angular Share Data Between Components is topic that may focus angular developers daily, so in this post, I will illustrate the different ways to share the data in angular components.

angular
angular shared library description


The following are the most easy way, I use in my projects to share data between components in angular

1- From parent to child

In the child component Inside the component and before component constructor , add the following input paramter:

    @Input() childId;
 

In the same child component, import the input tag

 import { Input } from '@angular/core';
 

In the parent html component, add the child tag as following

    <app-child [childId]="childId"></app-child>
 

In the parent ts component before constructor, define the childId paramter and pass the value you need, as the following

childId: number;

2- Using BehaviorSubject

Create a service class

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';

    class ChildDto{
        childId: number;
    }

    @Injectable({
        providedIn: 'root'
    })
    export class ChildDataService {

        constructor() { }

        private childSource = new BehaviorSubject([]);
        currentChild = this.childSource.asObservable();
        changeChild(childDto: ChildDto[]) {
            this.childSource.next(childDto)
        }

    }

For a good and clean code, you can move, the class ChildDto to a new file
In the parent component, call/inject the ChildDataService in the constructor

    import { ChildDataService } from 'service-location';

    constructor(
        private readonly childDataService: ChildDataService,
    )

    changeChild(){
      childDto: ChildDto[]=[]; // add your data
      this.childDataService.changeChild(childDto);
    }

In the child component, call/inject the ChildDataService in the constructor

    import { ChildDataService } from 'service-location';

    constructor(
        private readonly childDataService: ChildDataService,
    )

    callChild(){

      this.childDataService.currentChild.subscribe(result => {
       // do what you need with the results which changed in the parent.
      });
        
    }

Enjoy…!!!

We can help you to build such as software tools/snipts, you contact us from here

Exit mobile version