ng-show/ng-hide vs ng-if

These directives come into picture when we are trying to include a particular template /DOM elements depending upon certain conditions.So, which one is better to use ? How it is going to improve your application performance ? Let’s see. Below are the three key points that we should know about these directives.

  1. ng-if will removes or recreates  elements from DOM , by evaluating the value given to it by true/false. 
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to show/hide elements. 
  3. ng-if creates a child scope while ng-show/ng-hide does not .

So, it depends on the requirement to choose which directive to use.Do you want to load your DOM element or remove it entirely.But here comes the catch, if your DOM element consists ng-repeat or ng-options which evaluates the expressions and creates large number of DOM elements (basically iteration) will make your application watchers count go high, even though you are not showing that particular DOM element / template.This is the case where we are trying to include a template which has a lot of other elements and directives in use which they get evaluated every time we load, so to avoid this and make your application/page  performance quicker it’s better to use ng-if.As it evaluates your expression and removes or recreates the DOM element which will result in less number of watchers.

According to Misko Hevery,the number of watchers in an application should be less than 2000 for better performance.

Saying that if we have small elements like a div or paragraph etc., to display on conditions we can opt for ng-show / ng-hide.


2 thoughts on “ng-show/ng-hide vs ng-if

Comments are closed.