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

问题描述 投票:0回答:1

我正在尝试在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动态创建角度分量。为绘制此分量,我使用了ViewContainerRef。但是似乎这不是正确的方法。Coz我无法在td分量内创建我的CustomInputComponent通过这种方式。我想要做的是将CustomInputComponent嵌入每个td元素中。您可以看到我到目前为止写的内容here

javascript angular typescript
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.