使用 class 名称作为参考在 div 内附加组件

Appending component inside the div using class name as reference

可以使用 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);
}

但在我的例子中,我想使用 class 及其索引引用动态附加组件 例如

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);
}

应该很容易。只需尝试以下操作:

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