Creating an angular2 component with ng-content dynamically

There is the projectableNodes parameter for the vcRef.createComponent method

createComponent<C>(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][], ngModule?: NgModuleRef<any>): ComponentRef<C>;

You can use it to dynamically inject one component into another.

Let's say we have the following component

@Component({
    selector: 'card',
    template: `
        <div class="card__top">
            <h2>Creating a angular2 component with ng-content dynamically</h2>
        </div>
        <div class="card__body">
            <ng-content></ng-content>
        </div>
        <div class="card__bottom">
            <ng-content></ng-content>
        </div>
    `
})
export class CardComponent {}

We want to create it dynamically and insert some controls to its ng-content locations. It could be done like follows:

const bodyFactory = this.cfr.resolveComponentFactory(CardBodyComponent);
const footerFactory = this.cfr.resolveComponentFactory(CardFooterComponent);

let bodyRef = this.vcRef.createComponent(bodyFactory);
let footerRef = this.vcRef.createComponent(footerFactory);

const cardFactory = this.cfr.resolveComponentFactory(CardComponent);

const cardRef = this.vcRef.createComponent(
    cardFactory,
    0,
    undefined,
    [
        [bodyRef.location.nativeElement],
        [footerRef.location.nativeElement]
    ]
);

Plunker Example

See also

  • Why is projectableNodes an any[][]?

  • Pawel Kozlowski - Reactive parenting with Angular 2 - NG-BE 2016