Angular 4 ng-content select does not work with dynamically generated locked elements

I use ComponentFactoryResolver

to dynamically create an element to be inserted into my template, which I use ng-content

to navigate.

Everything works fine until I add the attribute select

to ng-content

. See this plunker which demonstrates the problem. If I remove the attribute content-top

from my template HeaderComponent

on line 63 app.ts

, the template looks as expected.

However, I need to use select

because there are two different template fragments that need to be inserted, so I cannot just delete it.

Any help was appreciated.

+3


source to share


1 answer


Conclusion in angular will only work with direct children. One way to do this can be used ngTemplateOutlet

to hoist content from a dynamic component:

<some-other-component>
    <ng-template content-host></ng-template>
    <ng-template top-content [ngTemplateOutlet]="topContent"></ng-template>
    <ng-template bottom-content [ngTemplateOutlet]="bottomContent"></ng-template>
</some-other-component>

      

component.ts

topContent: TemplateRef<any>;
bottomContent: TemplateRef<any>

const componentRef = viewContainerRef.createComponent(componentFactory);
const instance = componentRef.instance;
componentRef.changeDetectorRef.detectChanges();

this.topContent = instance.templates.find(x => x.place === 'top-content').templateRef;
this.bottomContent = instance.templates.find(x => x.place === 'bottom-content').templateRef;

      



where the template property is declared in the dynamic component

@ViewChildren(TranscludeMeToDirective) templates: QueryList<TranscludeMeToDirective>;

      

Plunger example

0


source







All Articles