我的目標是創建一個子組件並插入到父組件模板中。有些例子可以做到這一點。 但是,我在父組件中動態創建父組件模板(DOM元素),而大多數靜態顯示的示例使用捕獲元素創建模板。Angular 2:創建組件時動態插入捕獲元素(動態)
下面的代碼
app.component
import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver} from '@angular/core';
import {NewChildComponent} from "./newChild.component";
@Component({
selector: 'app-main',
templateUrl: 'app.component.html'
})
export class AppComponent {
@ViewChild('captureElement', {read: ViewContainerRef})
captureElement: ViewContainerRef;
constructor (private componentFactoryResolver: ComponentFactoryResolver) {
var childComponent = this.componentFactoryResolver.resolveComponentFactory(NewChildComponent);
var myArea = document.getElementById('myArea');
var myRow = document.createElement("div");
myArea.appendChild(myRow);
//I want to add the capture element #myCapture as a child of myRow
//Add something like this <div #captureElement></div> programmatically through JS/TS
// How can I do this?
// I then create the component
this.parent.createComponent(NewChildComponent);
}
app.component.html
<div id="myArea">
<!-- Static way of doing it -->
<!--<div #captureElement></div>-->
</div>
而不是在#captureElement
在子組件將被插入靜態定義,我想在父組件中動態創建它並使其成爲子組件。
這裏有一個問題清單我提到之前,我問過這個問題
- Angular2: Insert a dynamic component as child of a container in the DOM
- How to place a dynamic component in a container
- Angular 2 dynamic tabs with user-click chosen components
試過幾件事情
- 嘗試以編程方式創建
div
元素,#captureElement
作爲 屬性,但這不起作用。 - 試圖以編程方式創建隨機元素並使用
ViewContainerRef
來查找它。那也行不通。
非常感謝!這個HtmlContainer類將坐在哪裏?我的意思是......哪個組件? – am3
我創建了'HtmlContainer'作爲輔助類,它工作得很漂亮。再次感謝。你能否詳細說明HtmlContainer類正在做什麼? – am3
謝謝。如何維護動態組件以便我可以刪除它們?每次創建一個新的動態組件時,都嘗試在'addComponent'中保存一個對'componentRef.instance'的引用存儲的對象。在這個上調用'.destroy()'確實沒問題。有一個更好的方法嗎? – am3