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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With