Is there a way to insert dynamically a component as a child (not a sibling) of a DOM tag in Angular 2?
There are plenty of examples around there to insert a dynamic component as a sibling of a given ViewContainerRef
's tag, like (as of RC3):
@Component({
selector: '...',
template: '<div #placeholder></div>'
})
export class SomeComponent {
@ViewChild('placeholder', {read: ViewContainerRef}) placeholder;
constructor(private componentResolver: ComponentResolver) {}
ngAfterViewInit() {
this.componentResolver.resolveComponent(MyDynamicComponent).then((factory) => {
this.componentRef = this.placeholder.createComponent(factory);
});
}
}
But this generates a DOM similar to:
<div></div>
<my-dynamic-component></my-dynamic-component>
Expected result:
<div>
<my-dynamic-component></my-dynamic-component>
</div>
Using the SomeComponent
's ViewContainerRef
has the same result, it is still inserting the generated component as a sibling, not a child. I would be okay with a solution where the template is empty and dynamic components are inserted in the template (within the component selector tag).
The DOM structure is very important when using libraries like ng2-dragula to drag from a list of dynamic components and benefit from the model updates. The extra div is in the list of draggable elements, but outside the model, breaking the drag & drop logic.
Some say it is not possible (c.f. this comment), but it sounds like a very surprising limitation.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…