[email protected]      beta
Donate

AngularJs ng-if directives

Overview: Understanding ng-if directive, Use of AngularJS ng-if directives with an example, the difference between ng-if ng-show/ng-hide. ng-if add/remove HTML from DOM.

What is ng-if directives in Angularjs ?

In angularjs Ng-if directives is used to add or remove HTML content from DOM. The ng-if directives remove the HTML element only if the expression evaluates to false. And if the expression evaluates to true, then ng-if directives will recreate the HTML element and add it to the DOM.

Now you might be thinking what the use of ng-if is if we can do the same thing with ng-show and ng-hide directives that is hiding and displaying content. The angularjs ng-if directive is different from ng-show/ng-hide and also helps in performance wise.


Difference between ng-if vs ng-show ?

In angularjs ng-show and ng-hide directives used to change the visibility (show/hide) of HTML element. Directive ng-show is used to show the HTML element only if the expression evaluates to true. And ng-hide is the opposite of ng-show i.e., used to hide the HTML element. It adds classes to hide and display content.

Whereas the ng-if directives completely remove the element from DOM and recreate the portion of the element if an expression evaluates to true.

To make changes in the View or Model, angularjs uses the digest loop to watch for any changes in the app. And we know watches are expensive from a performance point of view. So by removing an element from the DOM, it removes all the watchers on those elements.

Ideally having few watches in any angular app makes to run faster and hence using ng-if is good for performance wise.


Example : Using ng-if in Angularjs.

Here in this article, we will display a welcome message ( HTML content ) when the checkbox is checked. We added ng-if attribute to our div which we want to add/ remove based on condition. The final code looks like as shown below.

<div ng-app> 
    Show HTML: <input type="checkbox" ng-model="myVar">
    <div ng-if="myVar">
      <h1>Welcome to Angular4pro.com</h1>
    </div>
</div> 

Try is yourself

Output:


  Popular Tag
  Recent Posts
  Follow Us
If you find these tutorials helpful then please donate. It will lead me to do more tutorials.
Donate