Creating a angular2 component with ng-content dynamically

后端 未结 1 650
北海茫月
北海茫月 2020-11-27 06:49

I would like to set the body of while instantiating a component dynamically using ComponentFactoryResolver.

I see that I

相关标签:
1条回答
  • 2020-11-27 07:08

    There is projectableNodes parameter for 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 in another.

    Let 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

    0 讨论(0)
提交回复
热议问题