rablentain
rablentain

Reputation: 6715

Angular2 directive, mouse movement event

I want to know how I can trigger a directive function when moving or clicking the mouse on some object.

I found this part of code which I think will do what I want. I am not sure about the syntax and what is actually happening though.

As part of the directive class I have this:

mousedown = new EventEmitter();
@HostListener('mousedown', ['$event'])
onMousedown(event) { 
    console.log(event); 
    this.mousedown.emit(event); 
}

Which, if I am clicking the div that has the directive, is printing the event to the console as expected. Although I am not sure on how the second line, this.mousedown.emit() is used.

What is actually called with the .emit() function?

Upvotes: 2

Views: 2026

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657238

mousedown = new EventEmitter(); seems redundant for your use case. If you prepend an @Output() annotation than you would listen to an mousedown event and immediately emit another one.

update

@Directive({
  selector: '[clickToOtherEvent]'
})
class EventTranslator {
  @Output() otherEvent = new EventEmitter();

  @HostListener('mousedown', ['$event'])
  onMousedown(event) { 
    console.log(event); 
    this.otherEvent.emit(event); 
  }
}

You can use the directive like

<button clickToOtherEvent (otherEvent)="doSomething()">test output</button>

The directive listens to mousedown event and emits an otherEvent you can again listen to.

Upvotes: 1

Related Questions