簡體   English   中英

將數據發送到 Angular 工具提示指令

[英]Sending Data to an Angular Tooltip Directive

我在網上找到了一個工具提示指令的例子。 我需要擴展它以便我可以將數據傳遞給工具提示並將其呈現在 *ngFor 中。 到目前為止我有

app.component.html

<div tooltipDirective [tooltipDataArray]="['Person1', 'Person2']">See tooltip!
  <ng-template #tooltipTemplate>      
      <div class="tooltip">   
          This is my tooltip!
      </div>      
  </ng-template>  
</div>

工具提示.directive.ts

  @Input() tooltipDataArray: string[];

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

  @HostListener('mouseenter')  onMouseEnter(): void { 
    console.log(this.tooltipDataArray);   
    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();
    }  
  }  

我可以記錄數據以便接收它,但我不確定 createEmbeddView、rootNodes 和 appendchild 是如何工作的(我正在使用一個示例)。 我想要的是包含 Person1、Person2 的工具提示。 我怎樣才能做到這一點?

StackBlitz 在這里

編輯:

我認為嘗試這樣做會讓我更接近我想要的並更好地解釋它,但現在工具提示根本沒有顯示。 這是 go 的正確方法嗎?

<div tooltipDirective [tooltipDataArray]="['Person1', 'Person2']">See tooltip!
 <ng-template #tooltipTemplate>      
   <div class="tooltip" *ngFor="let person of tooltipDataArray">
      {{ person }}
   </div>      
 </ng-template>  
</div>

完成此操作的一種方法是執行以下操作。

遍歷數組並構建div元素並將它們添加到viewdiv.tooltip中的rootNodes

  this.tooltipDataArray.forEach(el => {
      const child = document.createElement("div");
      child.innerText = el;
      this.renderer.appendChild(view.rootNodes[1], child);
    });

然后循環遍歷view上的節點並將它們添加到elementRef中,就像您現在所做的那樣。

view.rootNodes.forEach(node =>{
      this.renderer.appendChild(this.elementRef.nativeElement, node);
     } );

閃電戰

https://stackblitz.com/edit/angular-zr2ydx?file=app/tooltip.directive.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM