Why Components Need to Share Data

Angular apps consist of modular components that construct the UI. For example:

  • user dashboard may need data from a profile settings component.
  • weather widget should update itself according to the input of a location selector.

Below are five practical methods for component communication, accompanied by fresh examples.

data sharing between angular components


1. Parent to Child: Sharing Data with @Input()

Use @Input() to transfer data from a parent component to its children.

Step-by-Step

Parent Component (dashboard.component.ts):

export class DashboardComponent {  
  greetingFromParent = "Welcome from the Parent Component!";  
}  

Parent Template (dashboard.component.html):

<app-profile [welcomeText]="greetingFromParent"></app-profile>  

Child Component (profile.component.ts):

export class ProfileComponent {  
  @Input() welcomeText: string = '';  
}  

Child Template (profile.component.html):

<h2>{{ welcomeText }}</h2>  

Use Case: Display user-specific data (e.g., usernames, profile stats).

2. Child to Parent: Using @Output() to Emit Events

Sending data from child to parent by triggering an EventEmitter.

Child Component (settings.component.ts):

export class SettingsComponent {  
  @Output() messageEvent = new EventEmitter<string>();  
  
  sendUpdate() {  
    this.messageEvent.emit("Settings Updated Successfully!");  
  }  
}  

Child Template (settings.component.html):

<button (click)="sendUpdate()">Save Changes</button>  
<app-settings (messageEvent)="handleUpdate($event)"></app-settings>  

Parent Component (app.component.ts):

export class AppComponent {  
  handleUpdate(notification: string) {  
    console.log(notification); // "Settings Updated Successfully!"  
  }  
}  

Use Case: Confirm form submissions or trigger parent logic.

3. Sibling Communication Using a Shared Service with BehaviorSubject

Unrelated components should use a shared service with BehaviorSubject.

Step 1: Create a Communication Service

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

@Injectable({ providedIn: 'root' })  
export class CommunicationService {  
  private dataStream = new BehaviorSubject<string>('Initial Message');  
  currentData$ = this.dataStream.asObservable();  

  transmitData(newMessage: string) {  
    this.dataStream.next(newMessage);  
  }  
}  

Step 2: Send Data from SenderComponent

export class SenderComponent {  
  constructor(private commService: CommunicationService) {}  

  publishUpdate() {  
    this.commService.transmitData("New Data from Sender!");  
  }  
}  

Step 3: Receive Data in ReceiverComponent

export class ReceiverComponent implements OnInit {  
  receivedData: string = '';  

  constructor(private commService: CommunicationService) {}  

  ngOnInit() {  
    this.commService.currentData$.subscribe(data => {  
      this.receivedData = data;  
    });  
  }  
}  

Use Case: Real-time messages or shared app state (e.g., dark mode switch).

4. Direct Access Using ViewChild

Directly access child component properties/methods with @ViewChild.

Child Component (task-list.component.ts):

export class TaskListComponent {  
  taskCount: number = 5;  
}  

Parent Component (project.component.ts):

export class ProjectComponent implements AfterViewInit {  
  @ViewChild(TaskListComponent) taskList!: TaskListComponent;  

  ngAfterViewInit() {  
    console.log(this.taskList.taskCount); // Output: 5  
  }  
}  

Use Case: Triggering child methods (e.g., refreshing a data table).

5. Browser Storage for Persistent Data Sharing

Locally store data with localStorage or sessionStorage.

Example:

// Save user settings  
localStorage.setItem('userSettings', JSON.stringify({ theme: 'dark' }));  

// Retrieve data  
const settings = JSON.parse(localStorage.getItem('userSettings') || '{}');  
console.log(settings.theme); // "dark"  

Use Case: Maintain user sessions or application settings.

6. Using routes:
How to pass data between components using routes in Angular?

Best Practices for Clean Communication

  1. Avoid Overuse of ViewChild: Use services for scalability.
  2. Define Interfaces for Complex Data: Use types like User or Product.
  3. Lazy Load Modules: Load modules only when needed for better performance.

Angular Data Sharing

1: How do I share data between tabs or routes?

  • Use services with BehaviorSubject, or a state management library like NgRx.

2: Can I output more complex objects (not just strings)?

  • Yes! Use EventEmitter or services to output objects or arrays.

3: What is the difference between localStorage and sessionStorage?

  • localStorage persists indefinitely, while sessionStorage is cleared when the session ends.

Angular provides multiple options for inter-component communication, from simple @Input() & @Output() to advanced RxJS techniques.

This post is exclusively crafted for you 😊

Whether you're a beginner or an experienced Angular developer, I hope this guide clarifies your doubts about component data sharing. If you have any questions, feel free to share them in the comments—I’d love to help!

    Instance Of Java

    We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
    «
    Next
    Newer Post
    »
    Previous
    Older Post

    No comments

    Leave a Reply

    Select Menu