Reputation: 65
It is possible to append the component in to the view using the ViewContainerRef.
For Example, HTML File:
<div #Ref>it is possible to append the component here</div>
TS File:
@ViewChild("Ref", { read: ViewContainerRef })
public Ref: ViewContainerRef
appendComponent() {
const factory = this.componentFactoryResolver.resolveComponentFactory(
SingleframeComponent
);
this.Ref.createComponent(factory);
}
But in my case I want to append the component dynamically using the class and its index ref For Example
HTML File
<div #Ref>
<div class="appendComponentHere"></div>
<div class="appendComponentHere"> I need to append The component Here</div>
<div class="appendComponentHere"></div>
</div>
TS File
@ViewChild("Ref", { read: ViewContainerRef })
public Ref: ViewContainerRef
appendComponent() {
const factory = this.componentFactoryResolver.
//something like this i need to do
this.Ref.element .nativeElement.getElementsByClassName("fullslidebody")[1].createComponent(factory);
}
Upvotes: 2
Views: 1113
Reputation: 214067
It should be easy. Just try the following:
const viewRef = this.Ref.createComponent(factory).hostView as EmbeddedViewRef<any>;
const target = this.Ref.element.nativeElement.getElementsByClassName("fullslidebody")[1];
target.appendChild(viewRef.rootNodes[0]);
Upvotes: 2