[英]mouseleave with @HostListener not firing always in angular directive
我有一个 angular 指令,鼠标进入时我显示工具提示,鼠标离开时隐藏工具提示。 但有时 mouseleave 不会触发,因此工具提示不会隐藏。 见下图。 下面是我的指令的代码。 我对 angular 有点陌生。 所以有人可以帮忙吗?
import { Directive, Input, ElementRef, HostListener, Renderer2 } from '@angular/core';
import { ToolTipFactory, ToolTipRequester } from '../services/api/models/common.models';
import { ProductService } from '../services/api/product.service';
@Directive({
selector: '[tooltip]'
})
export class TooltipDirective {
@Input('tooltip') fieldName: string;
@Input() placement: string = 'top';
@Input() productType: string;
@Input() UOM: string;
@Input() horizontal: boolean = false;
@Input() fieldvalues: string;
@Input() model: string;
tooltipTitle: string;
tooltip: HTMLElement;
ToolTipReq: ToolTipRequester;
tooltipElement: any;
constructor(private el: ElementRef, private renderer: Renderer2, private productService: ProductService) { }
@HostListener('mouseenter', ['$event']) onMouseEnter(e: MouseEvent ) {
if (!this.tooltip) {
this.ToolTipReq = ToolTipFactory.createNew(this.productType);
this.ToolTipReq.fieldName = this.fieldName;
this.ToolTipReq.UOM = this.UOM;
this.ToolTipReq.FieldValues = this.fieldvalues;
this.ToolTipReq.Horizontal = this.horizontal;
this.ToolTipReq.Model = this.model;
const s = this.productService.getToolTip(this.ToolTipReq).subscribe(result => {
if ((result.Message != undefined && result.Message != '') || (result.Title != undefined && result.Title != '')) {
this.show();
}
},
error => {
s.unsubscribe();
},
() => {
s.unsubscribe();
}
);
}
}
@HostListener('mouseleave', ['$event']) onMouseLeave(e: MouseEvent) {
if (this.tooltip) {
this.hide();
}
}
show() {
this.create();
this.setPosition();
this.renderer.addClass(this.tooltip, 'ng-tooltip-show');
}
hide() {
this.renderer.removeClass(document.body, 'ng-tooltip-show');
this.renderer.removeChild(document.body, this.tooltipElement);
this.renderer.removeChild(document.body, this.tooltip);
this.tooltip = null;
}
create() {
this.tooltip = this.renderer.createElement('div');
this.renderer.appendChild(
this.tooltip,
this.tooltipElement
);
this.renderer.appendChild(document.body, this.tooltip);
this.renderer.addClass(this.tooltip, 'ng-tooltip');
this.renderer.addClass(this.tooltip, `ng-tooltip-${this.placement}`);
}
setPosition() {
}
}
请 go 通过链接https://github.com/angular/angular/issues/13911是的,当我们移动得非常快时,有时 Mouseleave 永远不会触发。 所以作为解决我所做的工作是在 mouseenter 事件本身超时 2-3 秒后调用工具提示隐藏方法。
window.setTimeout(() => {
if (!this.stillHovering) {
if (this.tooltip) {
this.hide();
}
}
}, 650);
}
@HostListener('mouseleave') onMouseLeave() {
this.stillHovering = false;
if (this.tooltip) { this.hide(); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.