Like in angular1 you can use events in angular2. What events good for? To make distant components to notify one to another.
How to send event
Everybody knows that for sending event you need to create some kind of channel. This channel will be used to publish(emit) event and to subscribe to event for getting notified .
Angular2 has its own EventEmitter class just for this scenario
import {Injectable, EventEmitter} from 'angular2/core';
@Injectable()
export class EmitterService {
private static _emitters: { [channel: string]: EventEmitter } = {};
static get(channel: string): EventEmitter {
if (!this._emitters[channel])
this._emitters[channel] = new EventEmitter();
return this._emitters[channel];
}
}
This service sets some channel (if no channel exists) and stores it in the private member
Challenge
In this post i want to demonstrate usage of events by bulding a refresh chart button, of the panel on which a flot component from older posts is located.
pressing on this button should refresh the data of the chart in the child flot component.
Click Event
Sending and catching click event is pretty straightforward:
Sending
<a href="#" panel-refresh="" (click)="chartRefresh();false">
<em class="fa fa-refresh"></em>
</a>
Catching
...
chartRefresh(){
this.getEntries();
}
...
The problem is to send custom event from parent component panel
to its child conmponent flot that will cause chart to redraw itself.
This event must be fired after data loaded through ajax request.
...
this.f.getFlotEntries()
.subscribe(entries => {
//here event is emitted
this.e.emit('Broadcast');
},
...
Full Code Of Panel Component
import {Component} from 'angular2/core'
import {FlotCmp} from './flot';
import {FlotService} from './FlotService';
import {EmitterService} from './EmitterService';
import {Observable} from 'rxjs/Observable';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Http, Response} from 'angular2/http';
@Component({
selector: 'panel',
providers: [],
template: `
<div class="panel panel-default">
<h2 class="panel-heading">
<div class="pull-right">
<a href="#" panel-refresh="" (click)="chartRefresh();false"><em class="fa fa-refresh"></em></a>
</div>
<div>panel heading</div>
</h2>
<flot class="panel-body" height="250px" width="100%"></flot>
</div>
`,
directives: [FlotCmp],
providers: [
FlotService,
EmitterService,
HTTP_PROVIDERS
]
})
export class Panel {
constructor(private f:FlotService,private e:EmitterService) {
this.e = EmitterService.get("channel_1");
this.getEntries();
}
getEntries(){
this.f.getFlotEntries()
.subscribe(entries => {
//here event is emitted
this.e.emit('Broadcast');
},
error => {
this.errorMessage = error;
console.log(error);
});
}
chartRefresh(){
this.getEntries();
}
}
Handling event
Child component flot responding to custom event from its parent.
...
this.emitter.subscribe(msg => {
$.plot( plotArea, this.dataset, this.options);
});
...