如何在 Angular 2 的同一个组件中使用多个 ng-content? [英] How to use multiple ng-content in the same component in Angular 2?

查看:25
本文介绍了如何在 Angular 2 的同一个组件中使用多个 ng-content?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的组件中显示不同的模板.只有一个会显示.如果 hasURLtrue,我想显示 .如果 hasURLfalse,我想显示 .

I would like to display different template in my component. Only one will show. If hasURL is true, I want to show the <a></a>. If hasURL is false, I want to show the <button></button>.

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

The problem if hasURL is false, the component show button, but the ng-content is empty. Because it's already read in the first "a></a>

请问有什么办法可以解决吗?

Is there a way to solve that please?

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

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

推荐答案

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

You can wrap ng-content in ng-template and use 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 示例

另见

Angular 9 演示

这篇关于如何在 Angular 2 的同一个组件中使用多个 ng-content?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆