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.
Turns out, you totally can. Run this demo in my JavaScript Demos project on GitHub. In Angular 1.
@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.
Angular Renderer2. If we want to listen to a mousemove event on some native DOM element and invoke its callback function, onMouseMove , we would call the . addEventListener in the following way: nativeElement. addEventListener("mousemove", onMouseMove);
For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method. To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With