I need to add the tappable
directive to the ion-card
component inside a custom component. I use an @Input() myInputBool
, something like:
<ng-container *ngIf="myInputBool">
<ion-card tappable>
<ng-container render="myContent"></ng-container>
</ion-card>
</ng-container>
<ng-container *ngIf="!myInputBool">
<ion-card tappable>
<ng-container render="myContent"></ng-container>
</ion-card>
</ng-container>
<ng-container #myContent>
This is my content
</ng-container>
Of course it does not work because there are no "render" option. So far my workaround was adding an inexistent variable in the ng-container
<ng-container *ngIf="thisVariableDoesNotExist else myContent"> </ng-container>
But it feels bad and hacky. Is there a better way to this?
ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.
ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.
In order to have a template rendered in that container, we use the *ngTemplateOutlet to pass a reference to an existing template, such as the one we created earlier. We use @Input to pass a TemplateRef to our 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.
I would use ngTemplateOutlet
instead of render
option:
<ng-container *ngTemplateOutlet="myContent"></ng-container>
See also
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