如何在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