Prem Parihar Prem Parihar - 1 year ago 197
TypeScript Question

How to place a dynamic component in a container

I want to create dynamic components and insert views of these components to a container.

I think this can be achieved by ViewContainerRef.

But I don't know, can we get

of any component? if yes then how?.
I am new to angularjs, if there are any other good solution available to handle this scenario, Please suggest me.

I think, I am pretty much near to the solution. Below is the code.


import {Component} from '@angular/core';
import {ContainerComponet} from './container.component'

selector: 'my-app',
template: `
<container> </container>
directives: [ContainerComponet]
export class AppComponent {

constructor() { }



import {Component, ComponentResolver, ViewContainerRef} from '@angular/core'
import {controlBoxComponent as controlBox} from './controlBox.component';

selector: 'container',
template: 'container'
export class ContainerComponet {
constructor(viewContainer: ViewContainerRef, private _cr: ComponentResolver) {

.then(cmpFactory => {
const ctxInjector = viewContainer.injector;
return viewContainer.createComponent(cmpFactory, 0, ctxInjector);



import {Component} from '@angular/core'
selector: 'controlBox',
template: 'controlBox'
export class controlBoxComponent {
constructor() { }


<container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox>

Expected Result

<controlbox _ngcontent-lsn-3="">controlBox</controlbox>

Answer Source

You can get the ViewContainerRef of the current component by

or from an element in the view of the current component

  selector: '...',
  directives: [OtherComponent, FooComponent],
  template: `
    <foo-component #foo></foo-component>
    <div #div></div>`)}

export class SomeComponent {
  // `ViewContainerRef` from an element in the view
  @ViewChild(OtherComponent, {read: ViewContainerRef}) other;
  @ViewChild('foo', {read: ViewContainerRef}) foo;
  @ViewChild('div', {read: ViewContainerRef}) div;

  // `ViewContainerRef` from the component itself
  constructor(private viewContainerRef:ViewContainerRef, private componentResolver: ComponentResolver) {}

  this.componentResolver.resolveComponent(ControlBox).then((factory) => {
      this.componentRef = this.other.createComponent(factory);
      // this.componentRef =;
      // this.componentRef = this.div.createComponent(factory);
      // this.componentRef = this.viewContainerRef.createComponent(factory);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download