How to pass data between two components in Angular 2

Ajay Dubey picture Ajay Dubey · Sep 5, 2016 · Viewed 77.8k times · Source

I am looking for solution to pass data to another component and similarly access methods of another component in other (both are parallel components).

For example i have two components home.ts and map.ts. I get some data into map.ts and need to pass that in home.ts and vice versa.

Answer

Abhijit Srivastava picture Abhijit Srivastava · Nov 18, 2017

You can transfer data using service.

Make a service that holds the data while you switch components. Below is an example.

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

@Injectable()
export class TransfereService {

  constructor(
    private router:Router,
    private companyServiceService:CompanyServiceService
  ) { }

  private data;

  setData(data){
    this.data = data;
  }

  getData(){
    let temp = this.data;
    this.clearData();
    return temp;
  }

  clearData(){
    this.data = undefined;
  }

}

Now Consider 2 components Sender and Reciever.

Senders code: This code sets the data to the service and navigates to the receiver.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class SenderComponent implements OnInit {         
  constructor(
    private transfereService:TransfereService,
    private router:Router) {}

  somefunction(data){
   this.transfereService.setData(data);
   this.router.navigateByUrl('/reciever');//as per router
 }
}

Reciever's Code: This code fetches the data from service and clears the data as well.

import { Router } from '@angular/router';
import { TransfereService } from './services/transfer.service';

export class RecieverComponent implements OnInit {  
 data = this.transfereService.getData();       
 constructor(
   private transfereService:TransfereService,
   private router:Router) {
      if(this.data){
        // do whatever needed
      }
      else{
        this.router.navigateByUrl('/sender');
      }
   }
}

You should check out Fireship Demo for the same. It's helpful.