【问题标题】:Angular 4 ng-content select not working on dynamically created transcluded elementsAngular 4 ng-content 选择不适用于动态创建的嵌入元素
【发布时间】:2018-01-02 23:46:46
【问题描述】:

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

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

但是我确实需要使用select,因为要注入两个不同的模板片段,所以我不能简单地删除它。

任何帮助表示赞赏。

【问题讨论】:

  • 如果我删除第 63 行的 content-top 属性,我看不出有什么区别。如果我从ng-content 中删除select,我会看到HeaderComponent 被渲染
  • Angular 仅包含直接子级。试试select="[content-host]"plnkr.co/edit/DXCBACANjufthKMgNeSE?p=preview
  • 对不起,你说的很对,我的意思是从第 18 行删除 select。我需要能够选择在 ng-template<ng-template content-host> 中被替换的元素无论如何都会被替换.在这种情况下,<h1 top-content> 将是顶层。
  • because there are two different template fragments to be injected so I can't simply remove it. 你能扩展你的例子吗?哪些片段也会被注入?

标签: javascript angular transclusion


【解决方案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;

在动态组件上声明模板属性的位置

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

Plunker Example

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多