【发布时间】:2017-01-31 04:04:44
【问题描述】:
我的目标是创建一个子组件并插入到父组件模板中。有一些例子可以做到这一点。 但是,我在父组件中动态创建父组件模板(DOM 元素),而显示的大多数示例都是使用捕获元素静态创建模板。
这是代码
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
尝试了几件事
- 试图用
#captureElement创建一个div元素作为 以编程方式设置属性,但这不起作用。 - 尝试以编程方式创建一个随机元素并使用
ViewContainerRef找到它。那也不行。
【问题讨论】:
标签: angular typescript angular2-template