[英]How to use an Angular2 Directive to inject DOM element?
I would like to create an Angular2 directive to display a tooltip when the user hovers over a list item.我想创建一个 Angular2 指令以在用户将鼠标悬停在列表项上时显示工具提示。
The Angular2 docs look like something like this: Angular2 文档看起来像这样:
@Directive({ selector: '[myUnless]' })
export class UnlessDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
How can I create a new template and inject into the viewContainer?如何创建新模板并注入 viewContainer? for example, a template like this:
例如,这样的模板:
<div class="tooltip">Some inner tooltip text</div>
I've seen examples of using the Dynamic component Loader, but not sure howit works exactly.我看过使用动态组件加载器的例子,但不确定它是如何工作的。
@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
) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.