我正在使用 ComponentFactoryResolver
动态创建要插入到我的模板中的元素,该模板使用 ng-content
进行嵌入。
在我将 select
属性添加到我的 ng-content
之前,一切都运行良好。请看this plunker这说明了问题。如果我在 app.ts
的第 63 行从我的 HeaderComponent
模板中删除 content-top
属性,模板将按预期呈现。
但是我确实需要使用 select
,因为要注入(inject)两个不同的模板片段,所以我不能简单地删除它。
感谢任何帮助。
最佳答案
angular 中的包含仅适用于直接子级。实现它的一种方法可能是使用 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;
在动态组件上声明模板属性的位置
@ViewChildren(TranscludeMeToDirective) templates: QueryList<TranscludeMeToDirective>;
关于javascript - Angular 4 ng-content select 不适用于动态创建的嵌入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347529/