Communicate Between Controllers

Difference between ngIf and ngShow-ngHide in AngularJS

While learning AngularJS, it is very important to learn basic fundamentals of the framework. Many time it seems like couple of functions works exactly same way then also they all exist. But there may be minor but important difference between them.

In AngularJS, I came across these kind of two directives which works almost same way at the first site. But when I read more, I found they look like same but not the same at all.

In this post, I will let you know the exact difference between ngIf and ngShow/ngHide. This post is in continuation of the previous posts of AngularJS to share my little knowledge with everyone.

Similarity

<div ng-if="element/exists">Show this Div</div>

<div ng-show="element/exists">Show this Div</div>

In AngularJS, ngIf & ngShow both will display element only if the expression passed in the directive returns true.

Difference

ngIf:
Will be inserted in DOM tree
Will not be inserted in DOM tree
ngShow/ngHide:
Will be visible in DOM tree
Will not be visible in DOM tree

ngIf – It will insert the DOM element only when the expression passed in the directive returns true, but if the expression passed returns false, it will not insert the DOM element in the DOM tree. It means when the DOM elements is removed from DOM tree all the handlers or any events etc… attached to elements will get lost. So next time when the expression returns true for the directive, it will not have any handlers or events attached to it. We have to attached them again explicitly. Moreover ngIf creates a child scope.

ngShow/ngHide – It will not remove the DOM element from the DOM tree if expression in the directive returns false. It will show/hide DOM element with display property of CSS as per the expression. All the handlers or any events attached to the elements will not be removed whatever the expression returns. Moreover ngShow/ngHide does not create scope.

Conclusion

I guess, ngIf is better when we needed the DOM to be loaded conditionally as it will help load page bit faster compared to ngShow/ngHide. But there is a thin line in deciding which of these directives should we use. It totally depends on the requirement of the DOM.

Web/ UI & Front-end developer based in Ahmedabad, GJ, India. Here to help/ discuss community to spread web awareness.

1 comments On Difference between ngIf and ngShow-ngHide in AngularJS

Leave a reply:

Your email address will not be published.