4

I am using the ComponentFactoryResolver to dynamically create an element to be inserted into my template, which uses ng-content for transclusion.

It all works wonderfully until I add a select attribute to my ng-content. Please see this plunker which demonstrates the problem. If I remove the content-top attribute from my HeaderComponent template on line 63 of app.ts, the template renders as expected.

I do however need to use select because there are two different template fragments to be injected so I can't simply remove it.

Any help appreciated.

7
  • If i remove content-top attribute on line 63 i don't see the difference. If i remove select from ng-content i see that HeaderComponent is rendered
    – yurzui
    Commented Jul 27, 2017 at 10:09
  • Angular transcludes only direct children. Try select="[content-host]" plnkr.co/edit/DXCBACANjufthKMgNeSE?p=preview
    – yurzui
    Commented Jul 27, 2017 at 10:11
  • Sorry, you're quite right, I meant remove the select from line 18. I need to be able to select elements that are replaced in the ng-template and <ng-template content-host> is replaced anyway. The <h1 top-content> will be the top level in this case.
    – serlingpa
    Commented Jul 27, 2017 at 10:24
  • because there are two different template fragments to be injected so I can't simply remove it. Can you expand your example? Which fragments will be also injected?
    – yurzui
    Commented Jul 27, 2017 at 10:28
  • 1
    plnkr.co/edit/YfX6CPLSFflhY1Qkiipt?p=preview
    – yurzui
    Commented Jul 27, 2017 at 10:57

1 Answer 1

1

Transclusion in angular will work only with direct children. One way to do it working might be using ngTemplateOutlet to lift up content from 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 templates property is declared on your dynamic component

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

Plunker Example

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.