使用指令将组件动态添加到子元素 [英] Add a component dynamically to a child element using a directive
本文介绍了使用指令将组件动态添加到子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用指令动态地将组件放置到子元素。
Trying to place a component dynamically to a child element, using a directive.
组件(作为模板):
@Component({
selector: 'ps-tooltip',
template: `
<div class="ps-tooltip">
<div class="ps-tooltip-content">
<span>{{content}}</span>
</div>
</div>
`
})
export class TooltipComponent {
@Input()
content: string;
}
指令:
import { TooltipComponent } from './tooltip.component';
@Directive({
selector: '[ps-tooltip]',
})
export class TooltipDirective implements AfterViewInit {
@Input('ps-tooltip') content: string;
private tooltip: ComponentRef<TooltipComponent>;
constructor(
private viewContainerRef: ViewContainerRef,
private resolver: ComponentFactoryResolver,
private elRef: ElementRef,
private renderer: Renderer
) { }
ngAfterViewInit() {
// add trigger class to el
this.renderer.setElementClass(this.elRef.nativeElement, 'ps-tooltip-trigger', true); // ok
// factory comp resolver
let factory = this.resolver.resolveComponentFactory(TooltipComponent);
// create component
this.tooltip = this.viewContainerRef.createComponent(factory);
console.log(this.tooltip);
// set content of the component
this.tooltip.instance.content = this.content as string;
}
}
问题在于这是创建一个兄弟姐妹而我想要一个孩子(见下文)
The problem is that this is creating a sibling and I want a child (see bellow)
结果:
<a class="ps-btn ps-tooltip-trigger" ng-reflect-content="the tooltip">
<span>Button</span>
</a>
<ps-tooltip>...</ps-tooltip>
想要的结果:
<a class="ps-btn ps-tooltip-trigger" ng-reflect-content="the tooltip">
<span>Button</span>
<ps-tooltip>...</ps-tooltip>
</a>
预先感谢您的帮助!
推荐答案
即使动态组件作为subling元素插入,您仍然可以使用以下元素将元素移动到所需位置:
Even dynamic component is inserted as subling element you can still move element to desired place by using:
this.elRef.nativeElement.appendChild(this.tooltip.location.nativeElement);
Plunker Example
这篇关于使用指令将组件动态添加到子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文