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

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

问题描述

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

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></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>

请问有办法解决吗?

        <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 Example

另请参见

Angular 9演示

Angular 9 demo

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

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