Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 452
Wain2021 Avatar asked Oct 26 '25 09:10

Wain2021


2 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>
like image 196
Andrei Avatar answered Oct 28 '25 02:10

Andrei


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.

like image 30
John Malkoln Avatar answered Oct 28 '25 03:10

John Malkoln



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!