javascript - Angular 4 ng-content select 不适用于动态创建的嵌入元素

标签 javascript angular transclusion

我正在使用 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>;

Plunker Example

关于javascript - Angular 4 ng-content select 不适用于动态创建的嵌入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347529/

相关文章:

javascript - 从远程服务器获取一个 JSON 文件(包含希伯来语值)并在 Node.js 中解析它

javascript 函数替换不起作用,为什么?

angular - 升级到 Angular 9 后,指令无法与 FormControl 一起使用

Angular - 只允许 ng-content 中的文本

Angular 9+ : nested ng-content and ContentChildren

javascript - 我怎样才能 "colour"屏幕的特定部分使用坐标?

javascript - 停止在 Angular.js 中缓存 View

Angular 服务和网络 worker

angular - 如何在 Angular 中生成服务器端 session 变量?

angularjs-scope - 结合 ng-repeat 和指令拒绝嵌入的内容访问外部范围?