Angular Quick(ish) Tip:<br />ng-if directive

Angular Quick(ish) Tip:
ng-if directive

October 14, 2015

So what is the ng-if directive and what can it do? It will conditionally include or exclude your HTML element if the condition inside the ng-if evaluates to true. Let's look at some examples.

<p ng-if="1 == 1">Show this please</p>

The ng-if is a built-in directive in Angular. It’s in the form of an attribute on this particular p tag. In the above example, 1 does equal 1, so the entire p tag will be rendered. Inside the quotes is what’s referred to as an Angular expression, just like the {{curly.brace.syntax}} we have been using in the past few articles of my Angular Beginners series of posts. Simple JavaScript can be put inside an expression. Things like math, but not much else can really be used.

<p ng-if="1 == 2">Show this please</p>

Nope. In the above code, 1 does not equal 2, so this p tag won’t get rendered. This type of logic really doesn’t get us anywhere. It gets more powerful when you evaluate something in your controller’s $scope. For instance, let’s say we have this controller set up, whith some data in it.

var brewitivity = angular.module('brewitivity', []);

brewitivity.controller('BrewController', function($scope){
	$scope.coffeePreferences = [
	   {
	      name: "Renee",
	      coffee: {
                roast: "Light Roast",
                size: "Tall",
                fixings: "Cream, Sugar, Cinnamon"
              }
	    },
	    {
	      name: "Rebecca",
	      coffee: {
	        roast: "Light Roast",
	        size: "Small",
	        fixings: ""
	      }
	   },
	   {
	      name: "Rich",
	      coffee: {
	        roast: "Pumpkin Spice",
	        size: "Medium"	 
                //property omitted     
	      }
	    }
	];
});

Basically I have my controller defined and an object on the $scope called coffeePreferences.

I can now use the ng-repeat directive like so:

<p ng-repeat="person in coffeePreferences">{{person.name}} likes a {{person.coffee.size}} {{person.coffee.roast}} with {{person.coffee.fixings}}.</p>

But what happens when the second two objects in coffeePreferences don’t have a value for the ‘fixings’ property? When rendered in the browser, the sentence is going to look like this, “Rebecca likes a small Light Roast with “. This is no good.

So here’s ng-if to the rescue.

<p ng-repeat="person in coffeePreferences">{{person.name}} likes a {{person.coffee.size}} {{person.coffee.roast}}<span ng-if="person.coffee.fixings"> with {{person.coffee.fixings}}</span>.</p>

Only if person.coffee.fixings has a truthy value, will the newly added span tag get rendered.

See the Pen ng-if directive by Rich Finelli (@richfinelli) on CodePen.

Falsy values

Angular interprets all these as falsy values:

{fixings: ""},
{fixings: false},
{}, //value omitted
{fixings: null},
{fixings: undefined}

An empty string is falsy and won’t render, but fixings: " " with a space in the string is considered truthy. The boolean of false will definately produce a falsy value, and omitting the fixings property altogether will produce a falsy value. Finally, and no surprise here, undefined and null both produce a falsy value. All of the above permutations will result in the span tag not getting rendered.

More with the if

Inside the ng-if you can also compare against a value of a property like this using comparison operators.

<span ng-if="person.coffee.fixings == 'Hazelnut Creamer'">{{person.coffee.fixings}}</span>
<span ng-if="person.coffee.fixings != 'Hazelnut Creamer'">{{person.coffee.fixings}}</span>

The first span will only get rendered if the value of person.coffee.fixings is set to “Hazelnut Creamer”. While the second span will only get rendered if person.coffee.fixings is not set to “Hazelnut Creamer”.

ng-show

Conversely, ng-show is functionally identical to ng-if, with one fundamental difference, instead of totally not rendering the span tag, it will instead, place a CSS class on it (ng-hide) that will essentially display: none it.

<span ng-if="person.coffee.fixings == true && person.coffee.fixings != 'Hazelnut Creamer'">{{person.coffee.fixings}}</span>

I haven’t done any real hard testing of this, but there are likely performance benefits of using ng-if, where ng-hide can be a little slower under certain circumstances.

That’s about it!

ng-if is simply looking to evaluate its expression as true or false. If true, it will get rendered and if false it won’t!

Mastering CSS: Book by Rich Finelli
Mastering CSS, the Book! Flexbox, Layout, Animations, Responsive, Retina, and more!
Mastering CSS, 2nd Edition, video course by Rich Finelli
Mastering CSS, Second Edition: 47 videos on how to make websites like a boss! Flexbox, Animations, Responsive, Retina, and more!
Back to top