June 20, 2022

Use ngIf else in angular template

In Angular template we can use if, if-then, if-else, if-then-else structures:

To acheive the required behavior, we have to create a template reference variable for the target element which needs to be shown in the given condition.

Lets say our component has boolean variable isValid, and we will check this variable in our example to display different UI elements based on truthy or falsy values.

Using simple if condition

For simple if condition, we can write:

<div *ngIf="isValid">
  this content will render when the isValid has truthy value.
</div>

Using if-then condition

We can also write the above code with if-then structure, which behaves exactly the same way as above, but have different syntax. We can write:

<div *ngIf="isValid;then thenBlock">
   this will never display
</div>
<ng-template #thenBlock>
   this content will render when the isValid has truthy value.
</ng-template>
Here we have defined a template reference variable (#thenBlock) on ng-template tag, and used it in the if-then structure to display it when this condition is true.

The above exmaple can also be written with ngIf and ngIfThen:

<ng-template [ngIf]="isValid" [ngIfThen]="thenBlock">
   this will never display
</ng-template>
<ng-template #thenBlock>
   this content will render when the isValid has truthy value.
</ng-template>

Using if-else condition

For case if with else, we can use ngIf and ngIfElse.

<ng-template [ngIf]="isValid" [ngIfElse]="elseBlock">
   this content will render when the isValid has truthy value.
</ng-template>
<ng-template #elseBlock>
   this content will render when the if condition is not truthy.
</ng-template>

Using if-then-else condition

We can also combine ngIf, ngIfThen, and ngIfElse.

<ng-template [ngIf]="isValid" [ngIfThen]="thenBlock" [ngIfElse]="elseBlock">
   this will never display
</ng-template>
<ng-template #thenBlock>
   this content will render when the isValid has truthy value.
</ng-template>
<ng-template #elseBlock>
   this content will render when the if condition is not truthy.
</ng-template>

No comments:

Post a Comment