Search code examples
angularangular12

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


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?


Solution

  • 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.