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>
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.
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.
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.
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.
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
Angular 9 demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With