skip to Main Content

How to pass the data from one component to another component

text

I need some suggestions and example codes
I want to know how to pass the data between the multiple components
is there another methods in the angular?

How to pass values from one component to another component through service or any other way, when components are not parent to child or child to parent?

3

Answers


  1. Answer:

    Using Angular Services:

    One effective way to pass data between Angular components that are not in a parent-child relationship is by utilizing a shared service. Here’s a step-by-step guide:

    1. Create a Shared Service:

      • Generate a service using the Angular CLI:
        ng generate service data-sharing
        
    2. Define Data in the Service:

      • In the generated service (data-sharing.service.ts), define a variable to hold the shared data.
        import { Injectable } from '@angular/core';
        
        @Injectable({
          providedIn: 'root',
        })
        export class DataSharingService {
          sharedData: any;
        }
        
    3. Inject the Service:

      • Inject the service in both components where you want to share data.

        import { Component, OnInit } from '@angular/core';
        import { DataSharingService } from '../data-sharing.service';
        
        @Component({
          selector: 'app-component1',
          templateUrl: './component1.component.html',
          styleUrls: ['./component1.component.css'],
        })
        export class Component1Component implements OnInit {
          constructor(private dataSharingService: DataSharingService) {}
        
          // Example: Set data in Component 1
          sendData() {
            this.dataSharingService.sharedData = 'Hello from Component 1';
          }
        }
        
        import { Component, OnInit } from '@angular/core';
        import { DataSharingService } from '../data-sharing.service';
        
        @Component({
          selector: 'app-component2',
          templateUrl: './component2.component.html',
          styleUrls: ['./component2.component.css'],
        })
        export class Component2Component implements OnInit {
          receivedData: any;
        
          constructor(private dataSharingService: DataSharingService) {}
        
          // Example: Get data in Component 2
          ngOnInit() {
            this.receivedData = this.dataSharingService.sharedData;
          }
        }
        
    4. Update UI Dynamically:

      • As the data changes in the service, the UI of both components will update dynamically.

    Alternative Methods:

    While services are a common and recommended way, there are other methods to achieve data sharing between components:

    • Event Emitters: Components can emit events that other components can subscribe to.
    • BehaviorSubject or Observables: Create an observable in a service and subscribe to it in multiple components.

    Remember to choose the method that best fits your use case and application architecture.

    Feel free to ask if you have any further questions or need clarification!

    Login or Signup to reply.
  2. if you use angular 17 you can use signals in a service.

    import { Injectable, signal } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class SampleService {
      count = signal(0);
    }
    

    in component one you can change this count and in component two you can listen to this change.

    component one:

    constructor(private sampleService: SampleService) {}
    
    this.sampleService.count.set(2);
    

    component two:

    import { Component, effect } from '@angular/core';
    .
    .
    .
    constructor(private sampleService: SampleService) {
      effect(() => console.log(this.sampleService.count()))
    }
    

    every time you change the count in component one or every where the component two will be noticed.

    Login or Signup to reply.
  3. As jabez has mentioned, services are likely the route that you want to go. You could also consider using a state management library, like ngrx, to handle state for your entire app. This would be more advanced, require more boilerplate, and has a bit of a learning cure, but centralizing your app’s state has many advantages with keeping data in sync and sharing data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search