【问题标题】:How to use an Angular2 Directive to inject DOM element?如何使用 Angular2 指令注入 DOM 元素?
【发布时间】:2017-02-07 09:53:56
【问题描述】:

我想创建一个 Angular2 指令,以便在用户将鼠标悬停在列表项上时显示工具提示。

Angular2 文档看起来像这样:

@Directive({ selector: '[myUnless]' })
export class UnlessDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
    ) { }
    this.viewContainer.createEmbeddedView(this.templateRef);
  }
}

如何创建新模板并注入 viewContainer?例如,这样的模板:

<div class="tooltip">Some inner tooltip text</div>

我看过使用动态组件加载器的示例,但不确定它是如何工作的。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:
    @Directive({ selector: '[tooltip]' })
    export class TooltipDirective {
    
      @HostListener('mouseenter') onMouseenter() {
        const factory = this.resolver.resolveComponentFactory(ExampleCompoent);
    
        this.viewContainerRef.createComponent(factory);
      }
    
      constructor(
        private viewContainerRef: ViewContainerRef,
        private resolver: ComponentFactoryResolver
      ) { }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 2016-07-07
      • 1970-01-01
      • 2016-09-09
      • 2016-06-17
      • 2013-10-26
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多