There are a variety of built-in Angular directives for showing and hiding content on a page. Ng-show/ng-hide and ng-if are commonly used directives for doing this. Ng-switch and ng-class could also be used to do this (albeit in different ways). This post will explain how ng-show and ng-if differ in their means of hiding content on a page.
Below is a simple example of ng-show in action. It’s a volume button that toggles between ‘Full Volume’ and ‘Muted’ when it is clicked.
[iframe src=”https://embed.plnkr.co/49oD9BTmWjr7Y4Rk5rsB” width=”100%” height=”450″]
There are two buttons in this html but only one is showing at a time. Each button has an ng-show directive on it. One button will show if the variable $scope.mute = true and the other if $scope.mute = false. This is because ng-show takes an expression as an attribute. If the expression is truthy, it shows that element on the page (and vice versa). Clicking the button there calls a function muteToggle (using ng-click) which toggles $scope.mute to true or false.
This same example could have been written with ng-hide, but with the true/false expressions reversed.
If you look at the HTML in the chrome developer tools, both buttons are there:
You’ll notice the hidden one is set to display:none;
Watch what happens to this same HTML if you use ng-if (which appeared in Angular 1.2) instead of ng-show.
[iframe src=”https://embed.plnkr.co/EfLFDVCgAEu8Ea66smIU” width=”100%” height=”450″]
Here’s the specific part of interest in the dev tools pane:
Only one button shows up in the HTML now. Just like the directive sounds, that particular element (in this case, a button) will only show up if the expression is true.
Ng-show/hide can show or hide an element on a page. They will still be in the DOM either way. Ng-if determines whether the element is actually added or removed from the DOM.
The potential problem with using ng-show/hide comes from Angular $digest loop. Ng-show can hide something from a user but not from the Angular $digest loop and watches. This can slow down performance if enough things are being watched on a page. By using ng-if, the DOM element will be removed and any watchers or event handlers with it. The major caveat to ng-if is that it brings in its own child scope into the app. Keeping track of scopes can be confusing at times, so be warned about that part of ng-if.
There might be cases when you need to still work with things (like event handlers) that are attached to hidden elements. This would be a use case for ng-show/hide.
But the general rule of thumb here is don’t load/keep anything into the DOM that you don’t need. You should generally use ng-if unless you explicitly need ng-show/hide.