born2net born2net - 3 months ago 22
TypeScript Question

How to listen to angular 2 events MANUALLY on a dependency injected instance?

If i have a component like

@Component({selector: 'todo-cmp'})
class TodoCmp {
@Input() model;
@Output() complete = new EventEmitter(); // TypeScript supports initializing fields

onCompletedButton() {
this.complete.next(); // this fires an event
}
}


and in another component I get a copy of it through DI as in:

...
class SomeOtherClass(){
constructor(todoCmp:TodoCmp){
// how do I listen to
...
}
...


How do I add an event listener manually inside "SomeOtherClass" and listen to any click events fired from the depenendcy injected instance of ToDoCmp..

something like todoCmp.addEventListener('complete',function(e){});

maybe? or something better in ng2?

TX

Sean.

Answer

First, EventEmitter.next() has been EventEmitter.emit() since alpha-45 or so.

Second, the method you're looking for is .subscribe()

class SomeOtherClass(){
  constructor(todoCmp:TodoCmp){
     todoCmp.complete.subscribe((result)=>{
        //result == arg passed into emit()  
     }))
 }

Note that this information is readily available in the docs - you should really check those out, as EventEmitter is much more capable than the event listeners you're used to.

Comments