动态加载组件 Angular 2

Dynamically load the components Angular 2

我正在尝试动态加载一组组件。我有一个数组,其中包含需要在 运行 时间加载的所有组件。以下代码循环遍历数组并为组件创建一个工厂。 `

gAfterViewInit() {
      this.loadcomponents();
  }
loadcomponents() {
      for (let i = 0; i < this.components.length; i++) {
          //this.sidetext[i] = this.components[i].sidetext;
          //this.section_ttile[i] = this.components[i].section_ttile;
          for (let j = 0; j < this.components[i].components.length; j++) {
              let termItem = this.components[i].components[j];
              let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component);
              let viewContainerRef = this.termHost.viewContainerRef;
              viewContainerRef.clear();
              let componentRef = viewContainerRef.createComponent(componentFactory);
              (<TermComponent>componentRef.instance).data = termItem.data;
          }
      }

` 这是我的模板

            <div class="div_for_ques" *ngFor="let component of components; let i=index">

                <div class="sec_two">
                    <ng-template term-host></ng-template>
                </div>
            </div>

但问题是动态加载的组件出现在先前加载的组件组件之上。我希望每个组件都在自己单独的 div 中。关于如何实现这一目标的任何建议? 以下是当前输出。

预期输出是两个这样的输入字段,但实际上只有第二个与第一个完全重叠。

您需要使用 @ViewChildren 才能获得容器的查询列表。

您的模板可以是这样的:

<div *ngFor="let v of views">
   <div #target></div>
</div>

并且您的代码将像这样实例化组件:

@ViewChildren('target', {read: ViewContainerRef}) container: QueryList<ViewContainerRef>;

ngAfterViewInit(){
  this.container.toArray().map((viewContainerRef, i) => {
    let componentFactory = this.resolver.resolveComponentFactory(this.components[i]); // actually that should be this.components[i].components[j] something in your case
    let componentRef = viewContainerRef.createComponent(componentFactory);
  });
}