Angular a 3 way If else condition in the component.html

Viewed 1886

I am using Angular 12 and in my component.html I need to have a 3 level condition.

For example:

I have a list and I need to check if it contains a string or not.

The true and false state both have a different output and finally I need to ELSE for any other condition.

So...First I have one condition:

<div *ngIf="list.includes('sometext') && listitem === null ">Condition 1</div>

Now a condition with the reverse of the above:

<div *ngIf="!list.includes('sometext') && listitem === null ">Condition 2</div>

And finally the ELSE:

<div>Condition 3 or Any other condition from the others above</div>

How can I do this?

3 Answers

The best way to solve this problem is to use ngSwitchCase insead of ngIf as shown below:

<container-element [ngSwitch]="true">
   <some-element *ngSwitchCase="list.includes('sometext') && listitem === null ">...</some-element>
   <some-element *ngSwitchCase="!list.includes('sometext') && listitem === null ">...</some-element>
   <some-element *ngSwitchDefault>Condition 3 or Any other condition from the others above</some-element>
</container-element>

You can implement it in such way:

<ng-container *ngIf="listitem; else noListItemTmpl">
    <div>Condition 3 or Any other condition from the others above</div>
</ng-container>

<ng-template #noListItemTmpl>
    <div *ngIf="list.includes('sometext')">Condition 1</div>
    <div *ngIf="!list.includes('sometext')">Condition 2</div>
</ng-template>

No nasty listitem === null checks.

nested if statements would make it easy to read.

<ng-container *ngIf="listitem === null; else third">
   <div *ngIf="list.includes('sometext')">Condition 1</div>
   <div *ngIf="!list.includes('sometext')">Condition 2</div>
</ng-container>
<ng-template #third>
   <div>Condition 3 or Any other condition from the others above</div>
</ng-template>
Related