我想编写一个自定义指令,该指令将根据div内部的某些逻辑动态添加组件,在该逻辑上我使用了我的自定义指令。
我尝试使用componentFactoryResolver和viewContainerRef.createComponent动态添加组件
<div myDirective>
<!-- dynamically add component through directive -->
<span>Hello</span>
</div>
// my custom directive
myDirective {
constructor( private element: ElementRef,
private renderer: Renderer,
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
ngOnInit() {
let componentFactory = this.componentFactoryResolver
.resolveComponentFactory(myComponent);
let componentRef = this.viewContainerRef
.createComponent(componentFactory, 0);
}
}
实际结果:在div之后创建了组件, 预期:组件应添加到div
答案 0 :(得分:1)
was historical reason用来将动态创建的组件放置在主机元素旁边。
但是您可以通过仅将创建的元素移动到host元素内来更改此行为。
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
constructor(private element: ElementRef,
private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
ngOnInit() {
const componentFactory = this.componentFactoryResolver
.resolveComponentFactory(DynamicComponent);
const componentRef = this.viewContainerRef.createComponent(componentFactory);
const host = this.element.nativeElement;
host.insertBefore(componentRef.location.nativeElement, host.firstChild)
}
}
答案 1 :(得分:0)
您可以为此使用ng-template:
<div>
<ng-template myDirective>
<!-- dynamically add component through directive -->
</ng-template>
<span>Hello</span>
</div>
检查我刚刚在Stackblitz上创建的示例。
希望这行得通!
注意:如果您想同时延迟和动态加载组件,请检查Manfred Steyer中的ng-conf演示文稿
更新:我在指令中添加了一些逻辑。另外,我不明白您为什么不想添加ng-template。