Skip to main content
Angular5 tutorials

Angular 4/5 Conditional Directives Uses and Example

Conditional statements of any language are very important. That help to activate functionality based on variable value.This angular 4 tutorial help to demonstrate conditional statement with example.

There are the following types of conditional statements available in angular 4:

  • [hidden]
  • *ng-if
  • *ng-switch

*ng-if then else

The NgIf-then-else directive is used when you want to display or remove an element based on a condition into the template. NgIf used variable value of an expression to add or remove the HTML element in DOM layout.

If the value of an expression is true then the element will add and If the condition is false, the element is attached to will be removed from the DOM. The else will use to show element if the value is false and necessary to show element.

The following syntax of ngif-then-else:

*ngIf="condition; then thenBlock else elseBlock"

The following syntax of the if statement:

*ngIf="condition;"

Simple Example Of *ngif :

<div *ngIf="isValid"> Data is valid. </div> 

[hidden] attribute

Angular 4 provides [hidden] attribute to show and hide elements based on the boolean variable. The difference between [hidden]='false' and *ngIf='false' is that the first method simply hides the element from DOM. The second method ngIf removes the element completely from the DOM.
The condition of an expression will be defined in the corresponding host component.

The syntax is:

[hidden]=""

Simple Example Of [hidden] :

<form #form ngNoForm action="https://whatever.site.I_access" method="get">
   <input type="hidden" name="scope" value="openid email">
   <input type="hidden" name="response_type" value="id_token token">
   <input type="hidden" name="client_id" value="myClientId">
   <input type="hidden" name="redirect_uri" value="https://my.redirect.com/">
   <input type="hidden" name="nonce" value="aNonceValue"> 

   <button type="submit">Submit</button>
 </form>

ngSwitch

The ngSwitch help to bind element with DOM-based on match condition, There is ngSwitchCase directive that holds matched condition expression,

If no conditions are matched within the switch statement it will check to see if there is an ngSwitchDefault the directive, if yes then render otherwise skip.

Simple Example Of ngSwitch:

<ul [ngSwitch]="gender">
  <li *ngSwitchCase="'m'">Male</li>
  <li *ngSwitchDefault>Female/li>
</ul>  

Leave a Reply

Your email address will not be published. Required fields are marked *