如何在 Angular 2 的同一个组件中使用多个 ng-content?

Posted

技术标签:

【中文标题】如何在 Angular 2 的同一个组件中使用多个 ng-content?【英文标题】:How to use multiple ng-content in the same component in Angular 2? 【发布时间】:2017-11-25 17:41:40 【问题描述】:

我想在我的组件中显示不同的模板。只有一个会显示。 如果hasURLtrue,我想显示<a></a>。 如果hasURLfalse,我想显示<button></button>

问题如果hasURL 为false,组件显示按钮,但ng-content 为空。因为它已经在第一个“a></a>

请问有办法解决吗?

        <a class="bouton" href=" href " *ngIf="hasURL">
            <ng-content>
            </ng-content>
        </a>

        <button class="bouton" *ngIf="!hasURL">
            <ng-content>
            </ng-content>    
        </button>

【问题讨论】:

【参考方案1】:

您可以将ng-content 包装在ng-template 中并使用ngTemplateOutlet

<a class="bouton" href=" href " *ngIf="hasURL">
    <ng-container *ngTemplateOutlet="contentTpl"></ng-container>
</a>

<button class="bouton" *ngIf="!hasURL">
    <ng-container *ngTemplateOutlet="contentTpl"></ng-container> 
</button>
<ng-template #contentTpl><ng-content></ng-content></ng-template>

Plunker Example

另见

How to conditionally wrap a div around ng-content

Angular 9 demo

【讨论】:

谢谢!它工作得很好。我仍然使用 Angular 2 而不是 Angular 4,所以我不得不使用 &lt;template&gt; 而不是 &lt;ng-template&gt; @dude 你能检查一下这个ng-run.com/edit/N7cnnC9HCm1cKlE88QFp吗? 我的错,它实际上似乎工作,但你不能输出两次 ng-content,只有在 *ngIf 包装它时提到这里,对不起。 为什么我们不能在多个模板中使用

以上是关于如何在 Angular 2 的同一个组件中使用多个 ng-content?的主要内容,如果未能解决你的问题,请参考以下文章