ngIf and ngElse

Posted 3 Nov 17 by Darren Welch

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>




Darren Welch

By

Darren Welch


  3 Nov 17


Contact me online

 Facebook

 Twitter

 Linked In

 Git Hub

Related Content




How to select all checkboxes using JQuery

24 Aug 2017




Useful Windows Tricks and Shortcuts

26 Jun 2017




Send ctrl alt delete over remote desktop

05 Feb 2017