簡體   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