Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I render an ng-container or ng-template without *ngIf?

Tags:

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?

like image 403
distante Avatar asked Aug 01 '17 08:08

distante


People also ask

Does ng-template get rendered?

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.

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

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.

How do I pass a ng-template?

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.

Can we use ng-template inside Ng-container?

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

I would use ngTemplateOutlet instead of render option:

<ng-container *ngTemplateOutlet="myContent"></ng-container>

See also

  • https://angular.io/api/common/NgTemplateOutlet#how-to-use
like image 121
yurzui Avatar answered Sep 17 '22 19:09

yurzui