Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 How to Implement if elseif else statement

Tags:

angular

I am new to Angular 8. I using Angular 8. Any help or hint would be greatly appreciated it!!

I trying to implement the following pseudo code:

if (condition1)
{
    print1
}
else if (condition2)
{
    print2
}
else
{
    print3
}

Here is the code that I am able to implement only if else

<ng-container *ngIf="(5>1);then resultOutOfRange else resultNA;">
</ng-container>
<ng-template #resultOutOfRange>
    <td  class="help-block">Result out of Range </td> 
</ng-template>
<ng-template #resultNA>
    <td>Result N/A</td>
</ng-template>
like image 312
jadeite1000 Avatar asked Aug 28 '26 15:08

jadeite1000


1 Answers

option 1: nested ngIf:

<ng-container *ngIf="condition1; then true1 else block2"></ng-container>
<ng-template #true1>true1</ng-template>
<ng-template #block2>
  <ng-container *ngIf="condition2; then true2 else true3"></ng-container>
  <ng-template #true2>true2</ng-template>
  <ng-template #true3>true3</ng-template>
</ng-template>

or alternatively, if possible, use ngSwitch:

<div [ngSwitch]="switchCondition">
  <ng-container *ngSwitchCase="case1">true1</ng-container>
  <ng-container *ngSwitchCase="case2">true2</ng-container>
  <ng-container *ngSwitchCase="case3">true3</ng-container>
</div>

ngSwitch works in cases where you need to switch based on a certain value, you could work your code to set some variable based on the result of whatever conditionals by assignign switchCondition in your else if block like:

if (condition1) {
  this.switchCondition = 'case1'
} else if (condition2) {
  this.switchCondition = 'case2'
} else {
  this.switchCondition = 'case3'
}

put that in some function and call when appropriate.

like image 78
bryan60 Avatar answered Aug 30 '26 11:08

bryan60



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!