Javascript 如何使用Angular2指令注入DOM元素?
我想创建一个Angular2指令,以便在用户将鼠标悬停在列表项上时显示工具提示 Angular2文档如下所示:Javascript 如何使用Angular2指令注入DOM元素?,javascript,angular,Javascript,Angular,我想创建一个Angular2指令,以便在用户将鼠标悬停在列表项上时显示工具提示 Angular2文档如下所示: @Directive({ selector: '[myUnless]' }) export class UnlessDirective { constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef ) { } th
@Directive({ selector: '[myUnless]' })
export class UnlessDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
<div class="tooltip">Some inner tooltip text</div>
@指令({selector:'[myuncher]})
出口类非关税指令{
建造师(
私有templateRef:templateRef,
私有viewContainer:ViewContainerRef
) { }
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
如何创建新模板并将其注入viewContainer?例如,这样的模板:
@Directive({ selector: '[myUnless]' })
export class UnlessDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
<div class="tooltip">Some inner tooltip text</div>
一些内部工具提示文本
我见过使用动态组件加载器的例子,但不确定它到底是如何工作的
@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
) { }
}