Angular2 – Sharing data between two components


angular-2-tutorialAngular2 is a fully component driven framework. Each component has its own html template where you can bind the data to this template through the respective component.

What if you need to share some data within two component? May be you need to modify the same data/variable inside multiple components.

For example,inside both navBarComponent and AppComponent, we need to change the header text of the nav bar.

First you need to write a service for storing data as angular Observebles.

import { Injectable } from '@angular/core';
import { Observable,Subject } from 'rxjs/Rx';

// lessonService to be shared within the application
export class TestService {

  constructor() { }

    // Observable string sources
  private selectedTestSource = new Subject<string>();

  // Observable string streams
  selectedTestSource$ = this.selectedTestSource.asObservable();

  // Service message commands
  setSelectedTestItem(param: string) {;


Now inject this service into Component 1.

  selector: 'app-sidenav',
  templateUrl: './sidenav.component.html',
  styleUrls: ['./sidenav.component.css']
export class SidenavComponent implements OnInit {

  constructor(private testService:TestService) { }

  ngOnInit() {


Now access this value inside the other component using a  subscriber.

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

export class AppComponent implements OnDestroy {

constructor(private testService:TestService) {
this.subscription = testService.selectedTestSource$.subscribe(
// add your code here

ngOnDestroy() {
// prevent memory leak when component destroyed




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s