Open In App

How To Share Data Between Child And Parent Directives And Components In Angular?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sharing data between child and parent components in Angular is important for building dynamic and interactive applications. This can be done through various concepts, including input and output bindings or using a shared service.

This article will explore how to use an Angular service to enable data communication, allowing both parent and child components to exchange and synchronize data effectively.

Prerequisites

Approach To Share Data

  • Create DataService using Angular's @Injectable decorator. Use BehaviorSubject to hold the initial data and provide an observable (currentData). Define changeData method to update the data in BehaviorSubject.
  • Create a parent component with an input field bound to a property (parentData). Add a button to trigger the updateData method. Inject DataService and call changeData in updateData to update the data. Subscribe to currentData in ngOnInit to display data from the service.
  • Create a child component to display data and include a button to modify it. Inject DataService and subscribe to currentData to get real-time updates. Implement modifyData method to update the data via changeData in the service.
  • Inject DataService into the parent and child components through their constructors. Ensure the service is provided at the root level (providedIn: 'root') for shared instance access.
  • Data changes in either the parent or child component will automatically reflect across both due to the reactive BehaviorSubject.
  • Use Angular’s dependency injection to ensure both components use the same service instance for data sharing.

Steps To Share Data Between Child And Parent Directives

Step 1: Install Angular CLI

If you haven’t installed Angular CLI yet, install it using the following command

npm install -g @angular/cli

Step 2: Create a New Angular Project

ng new angular-data-sharing --no-standalone
cd angular-data-sharing

Step 3: Install Angular Bootstrap

ng add @ng-bootstrap/ng-bootstrap

Step 4: Create Components and Service

ng generate component parent
ng generate component child
ng generate service data

Dependencies

"dependencies": {
"@angular/animations": "^18.2.1",
"@angular/common": "^18.2.1",
"@angular/compiler": "^18.2.1",
"@angular/core": "^18.2.1",
"@angular/forms": "^18.2.1",
"@angular/platform-browser": "^18.2.1",
"@angular/platform-browser-dynamic": "^18.2.1",
"@angular/router": "^18.2.1",
"@ng-bootstrap/ng-bootstrap": "^17.0.0",
"@popperjs/core": "^2.11.6",
"bootstrap": "^5.3.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
}

Folder Structure

PS
Folder Structure

Example: Create the required files as seen in the folder structure and add the following codes.

App Component Code

Below mentioned is the App Component which is the first component which gets loaded which an Angular Application is built. It initalizes all other components in order to run them.

HTML
<!-- app.component.html -->
<div class="container mt-5">
    <h1 class="text-success text-center">GeeksforGeeks</h1>
    <h3 class="text-center text-primary">Share data
        between child and parent directives and components
        in Angular
    </h3>

    <app-parent></app-parent>
</div>
JavaScript
//src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { ParentComponent } from './parent/parent.component';
import { ChildComponent } from './child/child.component';
import { DataService } from './data.service';

@NgModule({
    declarations: [
        AppComponent,
        ParentComponent,
        ChildComponent
    ],
    imports: [
        BrowserModule,
        FormsModule
    ],
    providers: [DataService],
    bootstrap: [AppComponent]
})
export class AppModule { }
JavaScript
//src/app/app.component.ts

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular-data-sharing';
}

Parent Component Code

Below mentioned is the Parent Component code that binds data using Angular's ngModel and communicates with a shared service to send data updates to the child component. The service allows for the exchange of data between the parent and child components using observables.

HTML
<!-- src/app/parent/parent.component.html -->
<div class="p-3 border border-primary rounded">
    <h2>Parent Component</h2>
    <input type="text" [(ngModel)]="parentData" class="form-control mb-3"
           placeholder="Enter data for service">

    <button (click)="updateData()" class="btn btn-primary">Update Data</button>

    <p class="mt-3">Data from Service: {{ serviceData }}</p>

    <app-child></app-child>
</div>
JavaScript
//src/app/parent/ parent.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
    parentData: string = '';
    serviceData: string = '';

    constructor(private dataService: DataService) { }

    ngOnInit() {
        this.dataService.currentData.subscribe(data => this.serviceData = data);
    }

    updateData() {
        this.dataService.changeData(this.parentData);
    }
}

Child Component Code

Below mentioned is the Child Component code that subscribes to the shared service to receive updates from the parent component and provides a button to modify the data, demonstrating two-way data sharing between the parent and child components.

HTML
<!-- src/app/child/child.component.html -->
<div class="p-3 border border-success rounded">
    <h3>Child Component</h3>
    <p>Data from Service: {{ serviceData }}</p>

    <button (click)="modifyData()" class="btn btn-secondary">Modify Data</button>
</div>
JavaScript
//src/app/child/child.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
    serviceData: string = '';

    constructor(private dataService: DataService) { }

    ngOnInit() {
        this.dataService.currentData.subscribe(data => this.serviceData = data);
    }

    modifyData() {
        this.dataService.changeData('Modified by Child Component');
    }
}

Services

Below mentioned is the DataService code that uses BehaviorSubject from RxJS to manage and share data between components. The service exposes an observable currentData and a method changeData to update the data, ensuring real-time synchronization between the parent and child components.

JavaScript
// data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private dataSource = new BehaviorSubject<string>('Initial Data');
  currentData = this.dataSource.asObservable();

  changeData(data: string) {
    this.dataSource.next(data);
  }
}

Open the terminal, run this command from your root directory to start the application

ng serve --open

Open your browser and navigate to http://localhost:4200

Output

1
How To Share Data Between Child And Parent Directives And Components In Angular

Article Tags :

Similar Reads