【问题标题】:how to pass templateRef to directive?如何将 templateRef 传递给指令?
【发布时间】:2021-03-31 13:52:52
【问题描述】:

我正在尝试以角度创建自定义工具提示指令,我想将 templateRef 作为输入属性从父组件传递给该指令,但 templateRef.elementRef 返回的是注释而不是模板内容。

指令:

@Directive({
  selector: '[tooltip]'
})
export class tooltipDirective {
  @Input('tooltip') tooltip: ElementRef<any>;
  @Input('placement') placement: string = 'bottom';

  constructor(private el: ElementRef, private renderer: Renderer2) {
    console.log(this.tooltip);
  }
}

父组件:

<div [tooltip]="tooltipTemplate"> show tooltip </div>

<ng-template #tooltipTemplate>
  <div class="tooltip">
    tooltip text
  </div>
</ng-template>

如何获取实际内容?

【问题讨论】:

  • 不要使用构造函数(永远……真的)……试试 AfterViewInit 钩子……
  • @MikeOne,Afterviewinit 也给出了相同的结果
  • 啊是的..对不起。我错过了您使用 Input 而不是 viewChild .. 说实话不知道如何传递..
  • 好的没问题,感谢您的回复

标签: angular


【解决方案1】:

你可以在getter中使用,但要小心,模板是TemplateRef。如果你想添加它,在构造函数中注入viewContainerRef,有些像:

  _tooltip:TemplateRef<any>
  @Input('tooltip') set tooltip(value)
  {
    this._tooltip=value
    this.viewContainer.createEmbeddedView(this._tooltip)
  }
  @Input('placement') placement: string = 'bottom';

  constructor(private viewContainer:ViewContainerRef) {}

更新:关于this.viewContainer.createEmbeddedView(this._tooltip)的使用,我们一般会做一些赞

    const embeddedViewRef = this.viewContainer.createEmbeddedView( this._tooltip );
    embeddedViewRef.detectChanges(); //<--this makes that if our template
                                     //has a variable and change, the tooltip
                                     //take account this change

然后,为了制作一个工具,我们可以使用Renderer2创建一个div,并将embeddedViewRef的所有节点添加到该div中

  const div = this.renderer.createElement("span");
  embeddedViewRef.rootNodes.forEach(n => {
    this.renderer.appendChild(div, n);
  });

辛苦的工作是计算位置,创建类工具提示并添加两个 HostListener 用于 mouseout 和 mouseover

【讨论】:

  • createEmbeddedView的作用是什么?
  • @jagjeet,我更新了答案以提供一些线索来制作工具提示,
  • @Elison 非常感谢这是完美的,只有一个问题,使用这种方法我无法在使用模板时向模板添加上下文
  • 我找到了解决方案,方法是使用辅助组件和指令,如果可行,我将在此处更新
猜你喜欢
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 2018-02-17
相关资源
最近更新 更多