Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 953
born2net Avatar asked Dec 22 '15 03:12

born2net


People also ask

Can we use two events together in Angular?

Turns out, you totally can. Run this demo in my JavaScript Demos project on GitHub. In Angular 1.

Which of the following is used for listening to user events in Angular?

@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.

Can I use addEventListener in Angular?

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);

How do you pass two arguments in EventEmitter?

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.


1 Answers

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.

like image 115
drew moore Avatar answered Sep 28 '22 09:09

drew moore