Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple ng-content in the same component in Angular 2?

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

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>
like image 291
Steffi Avatar asked Jun 22 '17 12:06

Steffi


People also ask

Can we use multiple Ng-content?

To add multiple ng-content, we need to add the select attribute as shown below. The select attribute property creates a mapping between the templates where these need to be transcluded.

What is a limitation of multiple slot content projection?

Known limitations of our implementation are as follows: You cannot data-bind the slot's name attribute. You cannot data-bind the slot attribute. You cannot dynamically generate slot elements inside a component's view.

What is Contentprojection in Angular?

Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.

What is the difference between Ng-content ng-container and ng-template?

To sum up, ng-content is used to display children in a template, ng-container is used as a non-rendered container to avoid having to add a span or a div, and ng-template allows you to group some content that is not rendered directly but can be used in other places of your template or you code.


1 Answers

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

See also

  • How to conditionally wrap a div around ng-content

Angular 9 demo

like image 144
yurzui Avatar answered Oct 16 '22 07:10

yurzui