Different ways to share data from one component to another

Sharing data from one component to another is the essential things to know when you are going to start writing application using angular 2 and above, this post will help you to get a content how many ways you can share data between one component to other so let begin.

1) Share data from Parent to Child: via Input()

This is probably the very common and straightforward method of sharing data. It works by using the Input() decorator to allow you to share data via template.

Parent Component

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

@Component({
  selector: 'app-parent',
  template: `<app-child [childMessage]="parentMessage"></app-child>`,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentMessage = "parent"
  constructor() { }
}

Child Component

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `{{message}}`,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

2. Child to Parent: Sharing Data via ViewChild()

Next is ViewChild  allows a one component to be injected into another, giving the parent access to its attributes and functions, here is very important things to note child won’t be available until after the view has been initialized.

Parent Component

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";

@Component({
  selector: 'app-parent',
  template: `Message: {{message}}
    <app-child></app-child>`,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent) child;

  constructor() { }

  message:string;

  ngAfterViewInit() {
    this.message = this.child.message
  }
}

Child Component

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

@Component({
  selector: 'app-child',
  template: `<div></div> `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hello I am child component"

  constructor() { }

}

3. Child to Parent: Share Data using Output() and EventEmitter

Here is the another way to share data here emit data from the child, which can be listed to by the parent. This approach is ideal when you want to share data changes that occur on things like button clicks, form entries, and other user events.

Parent Component

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

@Component({
  selector: 'app-parent',
  template: `
    Message: {{message}}
    <app-child (messageEvent)="receiveMessage($event)"></app-child>`,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

Child Component

mport { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>`,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hi I am child component"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

4) Share data using service

This is the easiest way to share data from parent child, child parent, siblings, to achieve this we need to create a services and then inject that service and share data let’s have a look.

Service file

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

@Injectable()
export class userDataService {  
   list:any;
   getUserData(){ 
      return this.list; 
   } 
   setUserData(data:any[]){
       this.list = data;
   }
}

Your first component

import { Component } from '@angular/core';
import {userDataService} from './userDataService';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title:String;
list:any;
constructor(private _userData: userDataService){
this.title = "Angular: Share data using service ";
this.list = [
{name:'Abc',age:'15'},

]
this._userData.setUserData(this.list);
}
}

Second Component 


import { Component,Input } from '@angular/core';
import {userDataService} from './userDataService';

@Component({
selector: 'app-list',
template:'',
styleUrls: ['./app.component.css']
})
export class Applist {
list : any[];

constructor(private _userData: userDataService){

}
fetchDataFromService(){

this.list = this._userData.getUserData();
}
}