动态创建带有 ng-content 的 angular2 组件

Creating an angular2 component with ng-content dynamically

我想在使用 ComponentFactoryResolver.

动态实例化组件时设置 <ng-content> 的主体

我发现我可以使用 ComponentRef 访问输入和输出,但无法设置 <ng-content>

请注意<ng-content>我计划设置可以包含简单的text/can跨越动态创建的组件

@Component({
    selector: 'app-component-to-project',
    template: `<ng-content></ng-content>`
})
export class ComponentToProject implements AfterContentInit {

    ngAfterContentInit() {
        // We will do something important with content here
    }

}


@Directive({
    selector: 'appProjectionMarker'
})
export class ProjectionMarkerDirective implements OnInit {

    constructor(private viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {
    }

    ngOnInit() {
        const componentFactory: ComponentFactory<ComponentToProject> = this.componentFactoryResolver.resolveComponentFactory(ComponentToProject);
        const componentRef: ComponentRef<ComponentToProject> = this.viewContainerRef.createComponent(componentFactory);
        // Question: How to set content before the child's afterContentInit is invoked
    }

}

@Component({
    selector: 'appTestComponent',
    template: `<div appProjectionMarker></div>`
})
export class TestComponent {}

vcRef.createComponent方法有projectableNodes参数

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

您可以使用它动态地将一个组件注入另一个组件。

假设我们有以下组件

@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 {}

我们想动态创建它并在其 ng-content 位置插入一些控件。它可以像下面这样完成:

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

另见