Angular 4 ng-content选择不处理动态创建的transcluded元素

时间:2017-07-27 10:03:55

标签: javascript angular transclusion

我正在使用ComponentFactoryResolver动态创建要插入我的模板的元素,该模板使用ng-content进行翻译。

在我向select添加ng-content属性之前,这一切都很有效。请参阅演示此问题的this plunker。如果我从content-top第63行的HeaderComponent模板中删除了app.ts属性,则模板会按预期呈现。

但我确实需要使用select,因为要注入两个不同的模板片段,因此我无法将其删除。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

角度中的横切仅适用于直接儿童。实现此功能的一种方法可能是使用ngTemplateOutlet来提升动态组件中的内容:

<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;

其中templates属性在动态组件上声明

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

Plunker Example

相关问题