繁体   English   中英

Angular 在所需组件内创建动态组件

[英]Angular Creating Dynamic Component Inside Desired Component

我正在尝试在html table的每个 td 子项中动态创建一个组件。 我创建了一个类似于以下代码的table组件(在app.component.html

<div class="container">
  <table class="table">
    <thead>
        <tr>
            <th scope="col" *ngFor="let column of columns">{{column}}</th>
         </tr>
    </thead>
    <tbody #preGrid id="focusItem">

    </tbody>
  </table>
</div>

app.component.ts文件如下所示。

ngOnInit() {
    let tableItem = document.getElementById("focusItem");
    let lastTR;
    for (let i = 0; i < 12; i++) {
      if (i % this.columns.length == 0) {
        let tr = document.createElement("tr");
        tableItem.appendChild(tr);
      }
      lastTR = this.getLastNode(tableItem);
      let td = document.createElement("td");
      lastTR.appendChild(td);

      const factory = this.resolver.resolveComponentFactory(
        CustomInputComponent
      );
      this.container.createComponent(factory);
    }
  }

我正在尝试通过动态使用ComponentFactoryResolver来创建角度ComponentFactoryResolver 。为了绘制这个组件,我使用了ViewContainerRef 。但似乎,这不是真正的方法。因为我无法通过这种方式在 td 组件中创建我的CustomInputComponent 我想要做的是,将 CustomInputComponent 嵌入到每个 td 元素中。您可以在这里看到我到现在为止写的内容。

您需要创建一个对象数组,其中包含要呈现的道具以及组件的类型,然后在 html 部分中,您可以使用ngFor循环来遍历该对象数组。 ngFor循环内部有多个ngSwitchCase来呈现当前迭代的正确控制。

请参阅此链接: https : //codeburst.io/angular-dynamic-forms-ng-switch-approach-4f267c01d2c6

暂无
暂无

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

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