17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 55: EventEmitter Service<br />

Section 55.1: Catching the event<br />

Create a serviceimport<br />

{EventEmitter} from 'angular2/core';<br />

export class NavService {<br />

navchange: EventEmitter = new EventEmitter();<br />

constructor() {}<br />

emitNavChangeEvent(number) {<br />

this.navchange.emit(number);<br />

}<br />

getNavChangeEmitter() {<br />

return this.navchange;<br />

}<br />

}<br />

Create a component to use the serviceimport<br />

{Component} from 'angular2/core';<br />

import {NavService} from '../services/NavService';<br />

@Component({<br />

selector: 'obs-comp',<br />

template: `obs component, item: {{item}}`<br />

})<br />

export class ObservingComponent {<br />

item: number = 0;<br />

subscription: any;<br />

constructor(private navService:NavService) {}<br />

ngOnInit() {<br />

this.subscription = this.navService.getNavChangeEmitter()<br />

.subscribe(item => this.selectedNavItem(item));<br />

}<br />

selectedNavItem(item: number) {<br />

this.item = item;<br />

}<br />

ngOnDestroy() {<br />

this.subscription.unsubscribe();<br />

}<br />

}<br />

@Component({<br />

selector: 'my-nav',<br />

template:`<br />

nav 1 (click me)<br />

nav 2 (click me)<br />

`,<br />

})<br />

export class Navigation {<br />

item = 1;<br />

constructor(private navService:NavService) {}<br />

selectedNavItem(item: number) {<br />

console.log('selected nav item ' + item);<br />

this.navService.emitNavChangeEvent(item);<br />

}<br />

}<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 180

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!