可以使用ViewContainerRef将组件附加到视图中。
例如, HTML文件:
<div #Ref>it is possible to append the component here</div>
TS档案:
@ViewChild("Ref", { read: ViewContainerRef })
public Ref: ViewContainerRef
appendComponent() {
const factory = this.componentFactoryResolver.resolveComponentFactory(
SingleframeComponent
);
this.Ref.createComponent(factory);
}
但在我的情况下,我想使用类及其索引ref动态追加组件 例如
HTML文件
<div #Ref>
<div class="appendComponentHere"></div>
<div class="appendComponentHere"> I need to append The component Here</div>
<div class="appendComponentHere"></div>
</div>
TS档案
@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);
}
答案 0 :(得分:2)
应该很容易。试试以下内容:
const viewRef = this.Ref.createComponent(factory).hostView as EmbeddedViewRef<any>;
const target = this.Ref.element.nativeElement.getElementsByClassName("fullslidebody")[1];
target.appendChild(viewRef.rootNodes[0]);
<强> Stackblitz Example 强>