Angular2 — Sharing data between two components

Supun Dharmarathne
technodyne
Published in
2 min readFeb 22, 2017
angular-2-tutorial

Angular2 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.

[sourcecode language=”javascript”]
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);
}

}
[/sourcecode]

Now inject this service into Component 1.

[sourcecode language=”javascript”]

@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);
}
}
[/sourcecode]

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

[sourcecode language=”javascript”]
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();
}

}
[/sourcecode]

--

--