How to make a if-else Angular template with only ng-container?
The code for the ngIf
directive expects to be passed a reference to a template (TemplateRef
) for the else branch, which it will call createEmbeddedView
on to display the nested content. Therefore, it makes no sense to try to use any other kind of element for the else content - it just won't work. You're able to nest an ng-container
inside the ng-template
if needs be, though.
This might seem unintuitive, but bear in mind that structural directives (i.e. ones that you call with a *
) are always represented as ng-template
under the hood, no matter what kind of element they're attached to - these two pieces of code are the same:
<ng-container *ngIf="contributeur.deb; else newDeb" >
...
</ng-container>
<ng-template #newDeb>
...
</ng-template>
<ng-template [ngIf]="contributeur.deb; else newDeb">
<ng-container>
...
</ng-container>
</ng-template>
<ng-template #newDeb>
...
</ng-template>
I do not love the standard Angular structure for if then else. Then I found an alternative solution with ngSwitch:
<ng-container [ngSwitch]="isFirstChoice(foo) ? 1 : (isSecondChoice(foo) ? 2 : -1)">
<ng-container *ngSwitchCase="1">
...first choice...
</ng-container>
<ng-container *ngSwitchCase="2">
...second choice...
</ng-container>
<ng-container *ngSwitchDefault>
...another choice...
</ng-container>
</ng-container>
To answer to your request I'd use this:
<ng-container [ngSwitch]="contributeur.deb && 'isDeb'">
<ng-container *ngSwitchCase="'isDeb'">
......
</ng-container>
<ng-container *ngSwitchDefault>
......
</ng-container>
</ng-container>
It bears mentioning that this simple alternative is perhaps more readable than many of the other options. Just using a second ng-container, and just 'not'-ing the condition with an exclamation mark to make the else section.
<ng-container *ngIf="contributeur.deb" >
[... HERE IS A RESULT 1]
</ng-container>
<ng-container *ngIf="!contributeur.deb">
[... HERE IS A RESULT 2]
</ng-container >