How to pass data between two components in Angular 2

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.

Leave a Comment