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

时间:2017-05-31 11:50:27

标签: angular angular-components

我希望在使用<ng-content>动态实例化组件时设置ComponentFactoryResolver的正文。

我看到我可以访问输入&amp;使用ComponentRef输出,但无法设置<ng-content>

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

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

1 个答案:

答案 0 :(得分:16)

projectableNodes方法

vcRef.createComponent个参数
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

另见