How to place a dynamic component in a container

You can get the ViewContainerRef of the current component by or from an element in the view of the current component

@Component({
  selector: '...',
  directives: [OtherComponent, FooComponent],
  template: `
    <other-component></other-component>
    <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 componentFactoryResolver: ComponentFactoryResolver) {}

  let factory = this.componentFactoryResolver.resolveComponentFactory(ControlBox)
  this.componentRef = this.other.createComponent(factory);
  // this.componentRef = this.foo.createComponent(factory);
  // this.componentRef = this.div.createComponent(factory);
  // this.componentRef = this.viewContainerRef.createComponent(factory);
  });
}

See also Angular 2 dynamic tabs with user-click chosen components

Leave a Comment