2017-05-31 113 views
5

我想設置<ng-content>的主體,同時使用ComponentFactoryResolver動態實例化組件。動態創建ng-content的angular2組件

我看到我可以使用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

使用'projectableNodes'參數https://stackoverflow.com/questions/41372334/why-is-projectablenodes-an-any – yurzui

+0

我是否也可以添加一個動態組件作爲'projectableNodes',這樣子對指令的父節點是可用的'@ ContentChild'? –

+0

由於它是一個可投影的'節點',我假設我只能通過'DOM'元素 –

回答

10

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

參見