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?
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.
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