使用类名作为引用在div中添加组件

时间:2017-10-26 09:20:02

标签: angular angular-components

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

1 个答案:

答案 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