【问题标题】:Angular Component is using ng-template from its childAngular 组件正在使用其子级的 ng-template
【发布时间】:2021-12-22 08:59:16
【问题描述】:

我有以下问题:

在我的 html 中,我有以下代码:

<form-section>
    <p>Hello</p>
    <form-section>
        <ng-template test-template>
            TEST
        </ng-template>
    </form-section>
</form-section>

输出是这样的:

Hello TEST
TEST

但它应该是这样的:

Hello
TEST

在我的form-section-component.html 中,我有以下结构:

<div *ngIf="actionTemplate">
    <ng-template [ngTemplateOutlet]="actionTemplate"></ng-template>
</div>

在我的form-section-component.ts:

@ContentChild(TemplateDirective, { read: TemplateRef, static: false }) actionTemplate: TemplateRef<any>;

所以这里的模板应该只在它存在时才显示。但不知何故,我的父组件也显示了模板。即使它没有模板。

【问题讨论】:

    标签: angular typescript ng-template


    【解决方案1】:

    在您的.html 文件中,您嵌套了&lt;form-section&gt; 标记。我对么? 在&lt;form-section&gt; 里面已经有一个ng-template

    顺便说一句,如果你想在组件标签之间插入一些内容,你应该使用ng-contenthttps://angular.io/guide/content-projection

    【讨论】:

    • 是的,这只是一个简化的例子。我有一个嵌套的 &lt;form-section&gt; 组件。 ng-template 应用于两个组件。它应该只应用于子组件
    • 更新了我的答案
    猜你喜欢
    • 2017-10-01
    • 2016-07-09
    • 2023-04-10
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2020-10-04
    • 2018-06-13
    • 2020-04-22
    相关资源
    最近更新 更多