ngIf and ngElse


How do you achieve a simple if / else using AngularJS.

In Javascript you would simply create an If/Else statement such as:

 

if (condition) {
    code to be executed if the condition is true
}
else {
    code to be executed if the condition is false
}

 

In Angular you could use ngIf for both, the If and Else.  You would reverse the condition using the ! character:

 

<div *ngIf="condition">div to display if the condition is true</div>
<div *ngIf="!condition">div to display if the condition is false</div>

 

Angular 4 has added some improvements, so now it's even easier to read. You can now tell ngIf the name of the template to load if the condition is false:

 

<div *ngIf="condition; else failedTemplate">div to display if the condition is true</div>
<ng-template #failedTemplate>template to display if the condition is false</ng-template>

 

To achieve an if/else if you could use ng-switch

 

<div ng-switch="id">
 <div ng-switch-when="1">...</div>
 <div ng-switch-when="2">...</div>
 <div ng-switch-when="3">...</div>
  <div ng-switch-default>...</div>
</div>

Comment