How do I use the Angular ngClass attribute?

Angular

Angular logo - ngClass

The Angular ngClass attribute allows you to programmatically determine if a CSS class will be applied to an HTML element.

We know that adding and removing CSS classes is a common JavaScript task. Quite often, it is the most efficient way to make style changes to one or more DOM elements. In fact, there is a great deal of power in this approach, with its ability to add or remove one CSS class that can cascade, causing dozens, hundreds or even thousands of child elements to change in appearance. But when leveraging Angular, there is no need to manually add or remove CSS classes to or from DOM elements; Angular just takes care of this, based on the state of your data. So, as you’ll see in the examples below, the most efficient way to go is to use the Angular ngClass attribute, which allows you to determine if a CSS class should be added to a DOM element, based on the result of a JavaScript expression.

Sometimes you may want to apply some CSS to an element, based on the value of some data. And sometimes you may want to apply other CSS when that data changes, or if it has a very specific value. With the ngClass attribute, Angular makes this kind of CSS logic arbitrary.

Example # 1

In Example # 1, we have our component. This code example is short, as there is only one thing to point out: the contentHighlighted property. This property is a boolean, so it will always be either true or false. We will pay attention to this value in our template.

Example # 2

In Example # 2, we have our Angular template. First, let’s take a look at the buttons. The first button sets the contentHighlighted property to true. It also has an ngIf attribute set so that when contentHighlighted is true, the button is destroyed. The second button functions in the exact opposite way: it sets the contentHighlighted property to false, and is destroyed if contentHighlighted is false. When you run the example code, you’ll notice that button’s toggle. That is to say: when you click one, it disappears (i.e. is destroyed) and then the other button appears (is created), and vice verse.

Next, look at the style element. There, we’ve defined a highlighted class. So, any element that has the highlighted class gets an outline and pastel yellow background.

Finally, we have the div with the ngClass attribute. Based on the syntax, we have declared that if the contentHighlighted property is true, then the highlighted class will be applied to this element. Conversely, if the contentHighlighted property is false, then the highlighted class will not be applied to this element. When you run the example code, you’ll see that as you toggle the buttons, the highlighted class is toggled on that element, and when it is applied, then that element gets the outline and pastel yellow background.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-ngClass

Sumary

The Angular Ngclass attribute allows you to programmatically apply one or more CSS classes to a DOM element. The CSS class is applied or removed, based on the result of a JavaScript expression, and any valid JavaScript expression can be used. This is much more efficient than manually applying or removing CSS classes. It just provides so much power when you’re trying to make small or large style changes to your component and its children.

Getting Started with Angular 1.x Custom Directives – Part III – The “restrict” property

Angular

Angular.js LogoLearn how the “restrict” property determines how your Angular.js directive can be invoked

In the second part of this series: Getting Started with Angular.js Custom Directives – Part II – The “replace” property, we learned about how to use the “replace” property when creating a custom Angular.js directive. This determines whether the element that your directive renders will be a child of the element that invoked it, or a complete replacement of that element.

In this article, we will learn about the “restrict” property that, which allows you to specify the ways in which your custom directive can be invoked.

Example # 1:

 

In Example # 1, we have created a custom Angular.js directive named: “uiWidget”. In addition to the “template” and “replace” properties that were discussed in previous articles, we have created a “restrict” property. This property allows you to specify the way in which the directive is invoked. Notice that the value is: “AECM”. These letters stand for:

  • A : Attribute
  • E : Element
  • C : Class
  • M : Comment

You can use any one of the values by itself, or any combination.

Example # 2:

In Example # 2, we have four snippets of HTML. In each case, we demonstrate a different way to invoke our custom Angular.js directive.

First, as an attribute of the HTML element. Notice how the attribute has no value. In our case, the mere presence of the attribute signals to Angular that our custom directive should be invoked.

Second, as an element. Although there is no such thing as a “ui-widget” HTML tag, Angular will recognize this element and invoke our custom directive.

Third, as a CSS class of the element.

Fourth, as a comment. This approach may seem a bit odd, but you can, in fact, trigger your custom Angular.js directive via an HTML comment.

HERE IS THE LINK TO THE WORKING EXAMPLE FOR THIS ARTICLE: http://examples.kevinchisholm.com/angular/directives/basics/html/part-iii.html

Summary

In this article, we learned about the “restrict” property of the object returned by an Angular directive. We discussed the four possible values for this property, and how each case differs.

The JavaScript “this” Keyword Deep Dive: Constructor Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword differs when instantiating a constructor (as opposed to executing the function).

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/2RFa3/

Example # 2

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/2RFa3/1/

Example # 3

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/2RFa3/2/

Summary

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

The JavaScript “this” Keyword Deep Dive: Nested Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword behaves inside of function declarations and expressions, even when nested 10 levels deep.

In the article: The JavaScript “this” Keyword Deep Dive: An Overview, we discussed a number of scenarios in which the JavaScript “this” Keyword has different meanings. In this article, we will concentrate on functions and methods.

It’s important to note that methods are functions. What makes a method a method is that the consumer of the code specifies an object, and then calls a method of that object.

Example # 1

In Example # 1, we have executed a function and a method. We have actually executed two functions, but the second function: “someMethod” is actually a method of the “bar” object. We know this because we have used the syntax: object.method().

It’s important to understand the difference between executing a function and a method.

Example # 2

foo = function (){ return this.music; }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/

In Example # 2, we have executed the function “foo”, which returns the value of “this.music”: “classical”. Both console.log statements return the value: “classical”, because since we are not inside of a method, the JavaScript “this” keyword refers to the window object, and at the top of the code, you’ll see that window.music is equal to “classical”.

Example # 3

foo = function (){ function bar(){ function baz(){ function bif(){ return this.music; } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/1/

In Example # 3, things get a bit silly, but the effect is the same. Even inside of nested functions, because none of these functions are methods, the JavaScript “this” keyword refers to the window object. And “this.music” is the same as “window.music”, which is equal to “classical”.

Example # 4

foo = function (){ function bar(){ function baz(){ function bif(){ function billy(){ function bobby(){ function betty(){ function jetty(){ function jimmy(){ function judy(){ return this.music; } return judy(); } return jimmy(); } return jetty(); } return betty(); } return bobby(); } return billy(); } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

In Example # 4, the function-nesting concept is taken to a ridiculous level. Nonetheless, the output is exactly the same: “this.music” is the same as “window.music”, which is equal to “classical”. It does not matter how deeply a function is nested. Unless it is a method of an object, the JavaScript “this” keyword will always refer to the window object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/84Yd4/2/

Summary

In this article we learned that when a function is not specified as a method of an object, the JavaScript “this” keyword refers to the window object. This is true even in the case of nested functions. In fact, no matter how many levels deep we nest functions, the JavaScript “this” keyword refers to the window object.

The JavaScript “this” Keyword Deep Dive: An Overview

JavaScript

JavaScript LogoLearn the subtle yet critical details that allow you to leverage the JavaScript “this” keyword.

In JavaScript, the “this” keyword is one of the most overly-used yet under-utilized aspects of the language. It is also one of the most mis-understood topics. While it facilitates more readable, expressive object-oriented JavaScript, improper use is a catalyst for confusing code that is difficult to debug.

Personally, I’ve struggled to understand the mystery. I’ve heard many unusually long-winded explanations, which I feel only contribute to the silliness. Simply put: In JavaScript, “this” refers to the object upon which a function is invoked. That’s it.

In JavaScript, “this” refers to the object upon which a function is invoked.

This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Example # 1

In Example # 1, we have added a property to the window object, named it: “music”, and assigned the value “classical”. In the line that follows, we output the value of “this.music”, and the result is: “classical”.

The reason for the output is simple: If you execute arbitrary code in the global context (i.e. outside of a function), then “this” refers to the window object. Executing arbitrary code in the global context is highly discouraged, but it is important to understand this behavior from a theoretical standpoint; in the global context: “this” will evaluate to the window object.

Example # 2

In Example # 2, we have added a function named foo, and then logged the output of that function’s execution. The resulting value is: “classical”. Some may have expected the output to be “blues”. This is a common mistake.

In the function “foo”, “music” is a variable. The “this” keyword has to do with objects, never variables (there is a very subtle scenario where “this” refers to a variable, which we will address in a later post). So the fact that there is a variable named “music” is completely meaningless in this example. The function “foo” does only one thing: it returns the value of this.music. In that function, “this” is the widow object, and the value of window.music is: “classical”. So, the variable “music” is completely ignored.

Example # 3

In Example # 3, we have added an object named “bar”. This object has two properties: “music”, which has a value of “jazz” and “getMusic”: a method that returns the value of bar’s “music” property.

The “getMusic” method has a line of code that you have seen in previous examples: “return this.music”. But why does that line of code return: “jazz”? The reason for this behavior is that when a function is a method of an object, the “this” keyword refers to the object upon which that function is invoked. In this case, the object is “bar”, and bar’s “music” property is equal to “jazz”, so “this.music” is equal to “jazz”.

Example # 4

In Example # 4, we have added the constructor function: “Baz”. “Baz” has a property named “music”, and it is equal to “rock”. It also has a property named “getMusic”, which is a method. The “getMusic” method returns the value of Baz’s “music” property.

You may be thinking that inside of the “Baz” constructor, the “this” keyword refers to the window object, as discussed in Example # 2. If we were to simply execute “Baz” (e.g. Baz() ), then yes, the property window.music would be overwritten and given the value of “rock”, and there would be a new global property named “getMusic”, which would return “rock”.

But that’s not what happens. After we create the constructor: “Baz”, we instantiate it, which results in a variable named “bif”, an instance of “Baz”. When you instantiate a JavaScript constructor function, the “this” keyword inside of that function refers to the instance object that the constructor returns.

HERE IS THE JS-FIDDLE.NET LINK

FOR EXAMPLE # 3:

Summary

In this article we discussed the high-level details of the JavaScript “this” keyword. We learned that it refers to the object upon which a function is invoked, and how it means different things in different scenarios. The scenarios we covered are: the window object, inside of a function, inside of a method, and inside of a constructor function.

Getting to Know the JavaScript element.classList Object

Object-Oriented JavaScript

JavaScript LogoNative JavaScript provides a way to access and manipulate all of the CSS classes that are assigned to an HTML element.

The JavaScript element.classList object is an instance of the JavaScript DOMTokenList object. It exposes one property and a number of methods that allow you to work with CSS classes that are assigned to an HTML element.

While it has been supported for some time by all major browsers, Microsoft Internet Explorer has, unfortunately, ignored JavaScript’s element.classList object until very recently (what a big surprise). If you need to support IE9 and below (and of course you do), then all bets are off. Bummer. That said, this object is nonetheless a super-helpful feature that makes CSS class manipulation a snap.

But what about jQuery?

There is no doubt that the jQuery methods hasClass(), addClass(), removeClass() and toggleClass() are all fantastic, but there ain’t nothin’ goin’ on under the hood that you can’t do yourself. And what is under the hood is tedious stuff like this:

This kind of code will soon join the ranks of the eight-track cassette and pagers. While that is the current reality of cross-browser CSS class list manipulation, the fact is that native JavaScript is always evolving, and as soon as Internet Explorer 10 becomes the IE standard, the JavaScript element.classList object will be yet another native JS tool to tuck into your belt.

The length Property

Even though the element.classList object is not an array, it is “array-like” in that it has a “length” property, and each CSS class name is represented by a numerically indexed property whose value is the name of that class (a string). This is super-helpful if you want to enumerate the classes that are members of this object. You could certainly grab an individual member’s value using bracket-notation: element.classList[0], a “for” loop, or the item() method, which is discussed next.

The JsFiddle link below demonstrates the classList object’s length property. The class “bar” is toggled when you click the element specified. On each click, the classList object’s length property is shown. Since a class is toggled, that length value changes with each click, which helps to demonstrate the dynamic nature of this property. Keep in mind that like any JavaScript array, the length property’s value will always be one higher than the index of the last element.

Here is the JsFiddle.net link for the classList object’s “length” property : http://jsfiddle.net/BmFZc/

The item() Method

The item() method allows you to reference a specific class name in the collection of class names. When you pass an integer to this method, it returns a string representation of the class name that matches that index. So keep in mind that this collection is zero-based. In the first JsFiddle link below, we manually reference a number of classes in the class list, using the item() method. In the second JsFiddle link below, we use a “for” loop to accomplish the same task.

Here is the JsFiddle.net link for the item() method: http://jsfiddle.net/N88x9/

Here is a second JsFiddle.net link for the item() method: http://jsfiddle.net/WE7gc/

The add() method

As you might expect, the add() method adds a class to the element’s class list. In the JsFiddle link below, you can see that the class “bar” is added to the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the add() method: http://jsfiddle.net/uzMAx/

The remove() Method

In the manner opposite to the add() method, the remove() method removes the specified class from the element’s class list. Much like the example for the add() method, you can see that the class “bar” is removed from the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the remove() method: http://jsfiddle.net/4h7m4/

The toggle() Method

The toggle() method will check to see if the element already has the specified class. If not, then it adds the class. If it does have the class, then it removes it. Depending on the scenario, this can minimize redundant code.

Here is the JsFiddle.net link for the toggle() method: http://jsfiddle.net/wWfNf/

The contains() Method

You can check to see if an element already has a class by using the contains() method. When you pass it a string name representing the class that you would like to check for, it returns true or false, indicating whether or not the element has the class you provided.

Here is the JsFiddle.net link for the contains() method: http://jsfiddle.net/wWfNf/

The toString() Method

The toString() Method simply returns a space-separated list of the classes that are applied to that element.

Here is the JsFiddle.net link for the toString() method: http://jsfiddle.net/GqzD5/

Summary

In this article we learned about JavaScript’s element.classList object. We demonstrated that while not exactly a JavaScript array, it is an “array-like” object with a length property, and some useful methods that allow you to work with the CSS classes that are assigned to an HTML element.

Helpful Links for the JavaScript element.classList object

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

http://blog.alexanderdickson.com/manipulating-classes-with-javascript

http://tiffanybbrown.com/2011/08/15/class-manipulation-with-classlist/