结构指令,位置工具提示

时间:2017-10-21 20:03:50

标签: angular tooltip ng-template

当我将鼠标悬停在文本“see tooltip”上时,我创建了一个基于ng-template内部显示工具提示的结构指令 工具提示显示正确,但它显示在顶部:0px左:屏幕的0px位置,我希望它显示在文本“看到工具提示”的正上方,我用方法“实现了elementRef的尺寸” getBoundingClientRect()“但我不知道如何在工具提示中应用它们。有什么想法吗?

tooltip.directive.ts

import { Component, Input, HostListener,  Directive, ElementRef, 
TemplateRef, ViewContainerRef,  ContentChild, ComponentRef } from 
'@angular/core';

@Directive({ selector: '[tooltipDirective]' })
export class TooltipDirective {
private tooltipId: string;
private dimensiones:{};
constructor(private elementRef: ElementRef,
          private viewContainerRef: ViewContainerRef) { }

@Input() parametroPlantilla: TemplateRef<any>;
@ContentChild( "tooltipTemplate" ) private tooltipTemplateRef: TemplateRef 
 <Object>;
@HostListener('mouseenter')  onMouseEnter(): void {    
this.viewContainerRef.createEmbeddedView(this.tooltipTemplateRef);
this.dimensiones = this.elementRef.nativeElement.getBoundingClientRect();   
}
@HostListener('mouseleave')  onMouseLeave(): void {        
 if (this.viewContainerRef) {
    this.viewContainerRef.clear();
  }  
 }  
}

display.component.ts

...Some stuff

<div tooltipDirective>See tooltip!
  <ng-template #tooltipTemplate >      
      <div>   
          This is my tooltip!
      </div>      
  </ng-template>  
</div>

1 个答案:

答案 0 :(得分:3)

我会通过在host元素中移动生成的工具提示来实现它,所以我只使用css规则来定义位置:

<强> tooltip.directive.ts

switch(Result) {
case 0:
  MessageBox.Show("It's bad!");
  break;
case -4:
  Thread.Sleep(20000);
  MyMethod.TryAgain();
  break;
default:
  MessageBox.Show("It's good");
  break;
}

<强> HTML

@Directive({ selector: '[tooltipDirective]' })
export class TooltipDirective {
  private tooltipId: string;

  constructor(
      private renderer: Renderer2,
      private elementRef: ElementRef,
      private viewContainerRef: ViewContainerRef) { }

  @Input() parametroPlantilla: TemplateRef<any>;

  @ContentChild( "tooltipTemplate" ) private tooltipTemplateRef: TemplateRef<Object>;

  @HostListener('mouseenter')  onMouseEnter(): void {    
    const view = this.viewContainerRef.createEmbeddedView(this.tooltipTemplateRef);
    view.rootNodes.forEach(node => 
      this.renderer.appendChild(this.elementRef.nativeElement, node));
  }

  @HostListener('mouseleave') onMouseLeave(): void {        
    if (this.viewContainerRef) {
      this.viewContainerRef.clear();
    }  
  }  
}

<强> CSS

<div tooltipDirective>See tooltip!
  <ng-template #tooltipTemplate>      
      <div class="tooltip">   <================ add class
          This is my tooltip!
      </div>      
  </ng-template>  
</div>

<强> Stackblitz example