I am trying to create a custom tooltip directive that accepts TemplateRef as input using Material Overlay and OverlayPositionBuilder, so we can pass the HTML template as input and display it inside the tooltip.
This is the code simple so far:
@Directive({
selector: '[rsTooltip]',
})
export class RsTooltipDirective implements OnInit, OnDestroy {
@Input() template: TemplateRef<any>;
...other properties
private _overlayRef: OverlayRef;
constructor(private _overlay: Overlay, private _overlayPositionBuilder: OverlayPositionBuilder, private _elementRef: ElementRef) {}
...NgOnInit handling tooltip position, etc
@HostListener('mouseenter')
showTooltip() {
if (this._overlayRef && !this._overlayRef.hasAttached()) {
const tooltipRef: ComponentRef<CustomTooltipComponent> = this._overlayRef.attach(new ComponentPortal(CustomTooltipComponent));
tooltipRef.instance.contentTemplate = this.contentTemplate;
}
}
@HostListener('mouseleave')
hideTooltip() {
if (this._overlayRef) {
this._overlayRef.detach();
}
}
...NgOnDestroy
}
CustomTooltipComponent is a simple component(represent tooltip) that simply receives the template and renders it.
So, the issue is whenever I hover over the host(directive host) element, the tooltip(CustomTooltipComponent) is displayed, but if I try to hover over the tooltip content(CustomTooltipComponent) it is no longer visible. Is there any way to handle this situation ? I want to update @HostListener('mouseleave') so it also checks the this._overlayRef.instance hover state; if user is hovering on top of CustomTooltipComponent it should not hide the tooltip.
CodePudding user response:
I'm not pretty sure if you can check event.target
Update, as @Keryanie say, we should ask about $event.toElement
instead $event.target
.
@HostListener('mouseleave', ['$event.target'])
@HostListener('mouseleave', ['$event.toElement'])
hideTooltip(target) {
if (this._overlayRef &&
!_this.overlayRef.overlayElement.contains(target)) ) {
this._overlayRef.detach();
}
}
but you should "detach", when mouseleave the tooltip