Angular2指令,鼠标移动事件

时间:2016-02-28 10:29:29

标签: angular

我想知道在某个对象上移动或单击鼠标时如何触发指令功能。

我发现这段代码我认为会做我想要的。我不确定语法和实际发生的事情。

作为指令类的一部分,我有这个:

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

如果我单击具有该指令的div,则会按预期将该事件打印到控制台。虽然我不确定如何使用第二行this.mousedown.emit()

使用.emit()函数实际调用了什么?

1 个答案:

答案 0 :(得分:1)

对于您的用例,

mousedown = new EventEmitter();似乎是多余的。如果您添加@Output()注释,而不是听mousedown事件,并立即发出另一个注释。

<强>更新

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

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

您可以使用

这样的指令
<button clickToOtherEvent (otherEvent)="doSomething()">test output</button>

该指令侦听mousedown事件并发出otherEvent您可以再次收听。

相关问题