【问题标题】:Dynamically load the components Angular 2动态加载组件Angular 2
【发布时间】:2017-11-05 07:39:31
【问题描述】:

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

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 中。关于如何实现这一目标的任何建议? 以下是当前输出。

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

【问题讨论】:

  • 如果您可以发布结果 dom 的图像会很有帮助。
  • 看看这个medium post
  • @micronyks 我已经编辑了问题
  • @Aravind 组件加载成功,但之前的组件与后面的组件重叠
  • 这听起来更像是一个 css 问题.. 尝试用 div 敲击你的 *ngFor 并将每个孩子设置为显示块,这样它们就会在另一个之下

标签: angular angular2-template angular2-directives


【解决方案1】:

您需要使用@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);
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-15
    • 2017-02-02
    • 1970-01-01
    • 2019-10-19
    • 2017-10-21
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多