My goal is to create a child component and insert into the parent component template. There are examples to do this. However, I create parent component template (DOM Elements) dynamically in the parent component while most of the examples shown statically create the template with the capture element.
Here's the code
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>
Instead of statically defining in #captureElement
where the child component would be inserted, I would like to create it dynamically in the parent component and make it a child component.
Here are a list of questions I referred before I asked this question
- 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
Tried a couple of things
- Tried to create a
div
element with a#captureElement
as an attribute programmatically but that doesn't work. - Tried to create a random element programmatically and use
ViewContainerRef
to find it. That doesn't work either.
We can't create a
ViewContainerRef
, as aViewContainerRef
only exists within a view.In 2.3.0,
attachView
was introduced which allows you to be able to attach change detection to the ApplicationRef. You can create some class that will encapsulate your logic like:this class is just helper that
1) resolves your dynamic component
2) then compiles component by calling
compFactory.create
3) after that registers its
changeDetector
(componentRef.hostView
extendsChangeDetectorRef
) by calling mentioned aboveappRef.attachView
(otherwise change detection won't work for your component)4) and finally appends the rootNode of your component to the host element
You can use it as follows:
Plunker Example
See also