ng-if Directive of AngularJS

Description

The ng-if directive allows us to conditionally insert an element in the DOM and remove an element from the DOM. It is based on a condition expression; if the value of the expression is false then the element will be removed from the DOM, or if the value of the expression is true then the element will be inserted into the DOM.

If you see my previous article Show and Hide Directives in AngularJS then of course you will think that both articles are the same and of course you will think, what is the difference between ng-if and the two other drictives ng-show and ng-hide, but there are some differences as follows.

ng-if vs ng-show and ng-hide

ng-if: Conditionally adding and removing the DOM element and completely remove and recreate the element in the DOM.

ng-show and ng-hide: ng-show only shows the element but does not recreate it in the DOM, ng-hide only hides the element but not remove it from the DOM.

This is the only the basic difference between ng-if and the two other drictives ng-show and ng-hide.

Use the following procedure to create a sample of the ng-if directive.

Step 1: First of all you need to add an external "angular.min.js" file to your application, To add this file to your application you need to download the "angular.min.js" file from the official website of AngularJS (the link is given as follows): AngularJS Official Wbsite

<!DOCTYPE html>

<html ng-app><!--ng-app tells AngularJS to be active in this portion of the page. In this case the entire document-->

   <head>

      <script src="angular.min.js"></script><!--Loading AngularJS File-->

   </head>


Step 2: Now make a check-box and two divisions and inside both divisions use the ng-if directive.
 

<body>

   <h3>Chack me:</h3>

   <input type="checkbox" ng-model="show"></br>

   <!-- ng-model links the form and the model. This means that any changes to the control update the data in your model, and when you change the model it updates the control-->

   <div ng-if="show" style="width: 300px; background-color: red;"><center><h2><B>Hello I am Sourabh Somani</B></h2></center></div>

   <div ng-if="!show" style="width: 300px; background-color: yellow;"><center><h2><B>Hello C-Sharp Corner</B></h2></center></div>

</body>

</html>
 
Output

When the Check-Box is unchecked:

Check-Box Unchecked
 
When the Check-Box is checked:  

Check-Box Checked


Similar Articles