我的子组件中有鼠标移动主机侦听器。
我在父组件中调用这个孩子。但是当用户移动鼠标时,有时鼠标移动没有检测到。但是如果我将主机侦听器代码移动到父组件,它的检测鼠标会无缝移动
@HostListener('mousemove', ['$event'])
@HostListener('touchmove', ['$event'])
onmousemove(e: MouseEvent) {
console.log("mousemove demo events",e.clientX,e.clientY)
}
谢谢你们。
我发现了问题. 我添加的主机侦听器特定于我的子组件的范围,因此在组件之外它没有检测到鼠标移动。 所以我添加了
ng 内容 在我的孩子中,并在孩子内部调用我的父母HTML内容,所以现在它检测到鼠标移动。例如
<child>
<div>test</div> //Parent component html
</child>
您可能需要将事件向上冒泡到父级(从子级(。
在子组件中:
@Output() mouseMoveEmitter = new EventEmitter();
然后在子组件中捕获 OnMouseMove 事件并发出它:
this.mouseMoveEmitter.emit(e);
在父 html 中,您可以捕获发出的事件,如下所示:
<your-child-component (mouseMoveEmitter)="onmousemove($event)"</your-child-component>
@HostListener('mousemove', ['$event'])
@HostListener('touchmove', ['$event'])
onmousemove(e: MouseEvent) {
console.log("mousemove demo events",e.clientX,e.clientY)
}
你以前用过这种方法吗?在哪里组合触摸和鼠标事件?我从未见过它,我不能肯定地说它不起作用,但我总是觉得它们是单独的事件类型。TouchEvents 是他们自己的打字稿类。我总是通过以下方式访问触摸位置:
event.changedTouches[0].clientX, event.changedTouches[0].clientY
而不仅仅是客户端X/clientY。我想浏览器可能正在做一些事情来包装或将它们翻译成同样的东西。