[英]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.