ArticleZip > Angular 4 Pass Data Between 2 Not Related Components

Angular 4 Pass Data Between 2 Not Related Components

When you're working on an Angular project, you might sometimes find yourself in a situation where you need to pass data between components that are not directly related. This can be a common scenario in larger applications with multiple components that need to communicate with each other. In this article, we'll explore how you can achieve this in Angular 4.

One way to pass data between unrelated components in Angular 4 is by using a shared service. Shared services allow components that are not directly related to communicate with each other by sharing data through a service. Here's how you can implement this:

1. **Create a Shared Service:**
Start by generating a new service using the Angular CLI. Run the following command in your terminal:

Plaintext

ng generate service data-sharing

This will create a new service file named `data-sharing.service.ts` in your project.

2. **Define Data Sharing Methods:**
In the `data-sharing.service.ts` file, define methods to store and retrieve data that needs to be shared between components. For example:

Typescript

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

   @Injectable()
   export class DataSharingService {
     sharedData: any;

     constructor() { }

     setData(data: any) {
       this.sharedData = data;
     }

     getData() {
       return this.sharedData;
     }
   }

3. **Inject the Shared Service:**
Next, you need to inject the `DataSharingService` into the components where you want to share data. In the components, you can then call the methods defined in the service to pass data between them.

4. **Pass Data Between Components:**
To pass data from one component to another, you can use the shared service you created. In the component that has the data to share, call the `setData()` method of the service to store the data. In the receiving component, call the `getData()` method to retrieve the shared data.

5. **Example Implementation:**
Let's see a simple example of how to pass data between two unrelated components using the shared service:

Typescript

// Component A
   export class ComponentA {
     constructor(private dataSharingService: DataSharingService) {}

     sendData() {
       this.dataSharingService.setData('Hello from Component A');
     }
   }

   // Component B
   export class ComponentB {
     sharedData: any;

     constructor(private dataSharingService: DataSharingService) {
       this.sharedData = this.dataSharingService.getData();
     }
   }

Implementing a shared service to pass data between unrelated components in Angular 4 provides a clean and efficient way to handle communication between different parts of your application. By following these steps, you can effectively share data and ensure seamless interaction between components in your Angular project.

×