Open In App

Define ng-if, ng-show and ng-hide

In this article, we will be explaining about ng-if, ng-show and ng-hide directive.

Syntax:



<element ng-if="expression"></element>

Example:

In the following Example, When there is any text in input element then div content will be shown otherwise it will be hidden.






<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body ng-app="">
 
Enter Text:<input type="text" ng-model="textcheck">
 
<div ng-if="textcheck">
<h1 style="color:green">GeeksforGeeks</h1>
</div>
 
</body>
</html>

Output:

When there is any text in the input field, Heading div is added to HTML DOM and is shown but when the input field is empty, div is removed and is not shown.

Syntax:

<element ng-show="expression"> </element> 

Example:

In the following Example, When their checkbox is selected then div content will be shown otherwise it will be hidden.




<!DOCTYPE html>
  <html>
    <script src=
    </script>
<body ng-app="">
 
<input type="checkbox" ng-model="check">
 
<div ng-show="check">
  <h1 style="color:green">GeeksforGeeks</h1>
</div>
 
</body>
</html>

Output:

When the Check box is selected, the HTML attribute div are set to show, otherwise hide them.

Syntax:

 <element ng-hide="expression"> </element> 

Example:

In this example, If checkbox is selected this means ng-hide attribute is true and the HTML elements will hide.




<!DOCTYPE html>
  <html>
    <script src=
    </script>
<body ng-app="">
 
Show DIV:<input type="checkbox" ng-model="check">
 
   <div ng-hide="check">
   <h1 style="color:green">GeeksforGeeks</h1>
</div>
 
</body>
</html>

Output:

When the Check box is selected, the HTML attribute div are set to hide, otherwise show them.

Basic Difference between ng-if, ng-show and ng-hide

ng-if directive ng-show directive ng-hide directive
The ng-if directive removes or recreates a portion of the DOM tree based on an expression, Instead of hiding it. The ng-show directive shows or hides the given HTML element based on the expression provided to the ng-show attribute The ng-hide directive shows or hides the given HTML element based on the expression provided to the ng-hide attribute .
ng-if can only render data whenever the condition is true. It doesn’t have any rendered data until the condition is true. ng-show can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives. ng-hide can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.

Hence, there is a considerable difference between ng-if, ng-show and ng-hide directive which makes them different for their usages .


Article Tags :