<!DOCTYPE html>
<html>
<head>
<base href="." />
<script type="text/javascript" charset="utf-8">
window.AngularVersionForThisPlunker = '4.4.3'
</script>
<title>Angular Example App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.8.18/dist/zone.js"></script>
<script src="https://unpkg.com/zone.js@0.8.18/dist/long-stack-trace-zone.js"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
<script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
<script src="config.js"></script>
<script>
System.import('app')
.catch(console.error.bind(console));
</script>
</head>
<body>
<app-root>loading...</app-root>
</body>
</html>
# Propagate data from one isolated component to components controlled by a router - Issue
This Angular code example demonstrates the issue of using `EventEmitter` to propagate data from one isolated component to components controlled by a router.
## Description of the issue
When Angular components are controlled by a router, only the selected one is executed at once. Consequently, if an external component shares data using `EventEmitter` with the components controlled by the router, only the selected one will receive the shared data.
## How to reproduce the issue
* Select one or more options in the dropdown menu on the left of the screen
* The selected options should be displayed as a list in the selected tab in the middle of the screen (the two tabs are components controlled by a router)
* Click on the second tab
* The list is now empty
* Go back to the first tab by clicking on it
* The list is no more displayed even in the first tab
## Solution
A solution to this issue is presented [here](http://plnkr.co/sJYnOO). Further details are available in this [blog post](http://blog.skyplabs.net/2017/11/30/angular-different-sharing-mechanisms-for-different-situations/).
var angularVersion;
if(window.AngularVersionForThisPlunker === 'latest'){
angularVersion = ''; //picks up latest
}
else {
angularVersion = '@' + window.AngularVersionForThisPlunker;
}
System.config({
//use typescript for compilation
transpiler: 'typescript',
//typescript compiler options
typescriptOptions: {
emitDecoratorMetadata: true
},
paths: {
'npm:': 'https://unpkg.com/'
},
//map tells the System loader where to look for things
map: {
'app': './src',
'@angular/core': 'npm:@angular/core'+ angularVersion + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + angularVersion + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + angularVersion +'/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms' + angularVersion + '/bundles/forms.umd.js',
'@angular/animations': 'npm:@angular/animations' + angularVersion + '/bundles/animations.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + angularVersion + '/bundles/animations-browser.umd.js',
'@angular/core/testing': 'npm:@angular/core' + angularVersion + '/bundles/core-testing.umd.js',
'@angular/common/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-testing.umd.js',
'@angular/compiler/testing': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler-testing.umd.js',
'@angular/platform-browser/testing': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-testing.umd.js',
'@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic-testing.umd.js',
'@angular/http/testing': 'npm:@angular/http' + angularVersion + '/bundles/http-testing.umd.js',
'@angular/router/testing': 'npm:@angular/router' + angularVersion + '/bundles/router-testing.umd.js',
'tslib': 'npm:tslib@1.6.1',
'rxjs': 'npm:rxjs@5.4.3',
'typescript': 'npm:typescript@2.2.1/lib/typescript.js',
'jquery': 'npm:jquery@3.2.1/dist/jquery.min.js',
'bootstrap-select': 'npm:bootstrap-select@1.12.4/dist/js/bootstrap-select.min.js'
},
//packages defines our app package
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
});
//main entry point
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule)
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class SharedService {
private selectedChoices: EventEmitter<string[]> = new EventEmitter<string[]>();
getSelectedChoices(): EventEmitter<string[]> {
return this.selectedChoices;
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-router',
template: `
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" routerLinkActive="active"><a routerLink="/receiver-1" role="tab">Receiver 1</a></li>
<li role="presentation" routerLinkActive="active"><a routerLink="/receiver-2" role="tab">Receiver 2</a></li>
</ul>
<div class="tab-content">
<router-outlet></router-outlet>
</div>
`
})
export class RouterComponent {
constructor() { }
}
import { Component } from '@angular/core';
import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-emitter',
template: `
<div class="panel panel-primary">
<div class="panel-heading">
Emitter
</div>
<div class="panel-body">
<div class="form-group">
<label for="choices">Data to send to the receivers</label>
<select appSelectpicker id="choices" class="selectpicker form-control" title="Choices" multiple [(ngModel)]="choices" (ngModelChange)="updateSelection()">
<option>Choice 1</option>
<option>Choice 2</option>
<option>Choice 3</option>
</select>
</div>
</div>
</div>
`
})
export class EmitterComponent {
choices: string[];
constructor(
private shared: SharedService
) { }
updateSelection(): void {
this.shared.getSelectedChoices().next(this.choices);
}
}
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-receiver-1',
template: `
<div class="panel panel-default" style="margin-top: 1em;">
<div class="panel-heading">
<h3 class="panel-title">Selected choices</h3>
</div>
<div class="panel-body">
<ul *ngFor="let choice of selectedChoices">
<li>{{ choice }}</li>
</ul>
</div>
</div>
`
})
export class Receiver1Component implements OnInit, OnDestroy {
selectedChoices: string[] = [];
private selectedChoicesStream: Subscription;
constructor(
private shared: SharedService
) { }
ngOnInit() {
this.selectedChoicesStream = this.shared.getSelectedChoices().subscribe(
( selectedChoices ) => {
this.selectedChoices = selectedChoices;
}
);
}
ngOnDestroy() {
if (this.selectedChoicesStream) {
this.selectedChoicesStream.unsubscribe();
}
}
}
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { SharedService } from '../services/shared.service';
@Component({
selector: 'app-receiver-2',
template: `
<div class="panel panel-default" style="margin-top: 1em;">
<div class="panel-heading">
<h3 class="panel-title">Selected choices</h3>
</div>
<div class="panel-body">
<ul *ngFor="let choice of selectedChoices">
<li>{{ choice }}</li>
</ul>
</div>
</div>
`
})
export class Receiver2Component implements OnInit, OnDestroy {
selectedChoices: string[] = [];
private selectedChoicesStream: Subscription;
constructor(
private shared: SharedService
) { }
ngOnInit() {
this.selectedChoicesStream = this.shared.getSelectedChoices().subscribe(
( selectedChoices ) => {
this.selectedChoices = selectedChoices;
}
);
}
ngOnDestroy() {
if (this.selectedChoicesStream) {
this.selectedChoicesStream.unsubscribe();
}
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmitterComponent } from './emitter/emitter.component';
import { Receiver1Component } from './receiver-1/receiver-1.component';
import { Receiver2Component } from './receiver-2/receiver-2.component';
import { RouterComponent } from './router/router.component';
import { SelectpickerDirective } from './selectpicker/selectpicker.directive';
import { SharedService } from './services/shared.service';
@NgModule({
declarations: [
AppComponent,
EmitterComponent,
Receiver1Component,
Receiver2Component,
RouterComponent,
SelectpickerDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [
SharedService
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
Angular Example App
</a>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row content">
<div class="col-sm-3 sidenav">
<app-emitter></app-emitter>
</div>
<div class="col-sm-9">
<app-router></app-router>
</div>
</div>
</div>
`
})
export class AppComponent { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Receiver1Component } from './receiver-1/receiver-1.component';
import { Receiver2Component } from './receiver-2/receiver-2.component';
const routes: Routes = [
{ path: '', redirectTo: '/receiver-1', pathMatch: 'full' },
{ path: 'receiver-1', component: Receiver1Component },
{ path: 'receiver-2', component: Receiver2Component }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
import { Directive, ElementRef, OnInit } from '@angular/core';
import 'jquery';
import 'bootstrap-select';
@Directive({
selector: '[appSelectpicker]'
})
export class SelectpickerDirective implements OnInit {
constructor(
private el: ElementRef
) { }
ngOnInit() {
jQuery(this.el.nativeElement).selectpicker();
}
}