繁体   English   中英

动态加载组件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);
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM