Search code examples
javascriptangulartypescriptangular2-templateangular2-services

Passing value between two angular 2 component typescript files


I have two components that are not parent Components and those are child components but I need to pass data from component A to component B. example: component A.ts has an array of data example :

my data [
   {'name':'some a','email':'some [email protected]','grades':{}},
   {'name':'some b','email':'some [email protected]','grades':{}}
  ]

need to pass that my data to component B.ts


Solution

  • If they don't have a parent/child relationship, the best way is a shared service injected into the constructors of A and B.

    component A:

    constructor(private sharingService: SharingService) { }
    
    public myArray = [];
    
    func() {
        ...
        this.sharingService.save(this.myArray);
    }
    

    Service:

    import { Injectable, } from '@angular/core';
    
    @Injectable()
    constructor() {}
    
    private array = [];
    
    save(array) {
        this.array = array;
    }
    
    fetch() {
        return this.array;
    }
    

    component B:

    constructor(private sharingService: SharingService) { }
    
    public yourArray = this.sharingService.fetch();
    

    There's a good tutorial on services and component interaction on the Angular site.