Home > Angular2 > Angular2 – Sharing data between two components

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
@Injectable()
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) {
    this.selectedTestSource.next(param);
  }

}

Now inject this service into Component 1.


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

  constructor(private testService:TestService) { }

  ngOnInit() {
  }

changeTest(testId:string){
  this.testService.setSelectedTestItem(testId);
}
}

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(
testId=&gt;{
// add your code here
});
}

ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}

}

 

Advertisements
Categories: Angular2
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: