Style HTML elements in Angular using ngClass

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

When we want to add multiple CSS classes on our HTML elements, and possibly even by using some kind of condition, things might get complicated… Fortunately ngClass is here to help! We will learn about the various ways ngClass allows us to conditionally add multiple classes to HTML elements using a variety of different data structures.

[00:01] Here we have a very simple component with some predefined styles. If you need to add multiple CSS class to DOM element within our component, for instance, this div here, we can use the ng-class.

[00:15] Let's use here ng-class's variable, which we define directly inside our component here. This variable is directly bound to that ng-class definition up here.

[00:31] What we can do now is to directly here specify the name of the CSS class, and you can see how it gets applied to our DOM element. We can also directly add a space here and add further classes. As you can see, all of them get applied.

[00:48] Another possibility is to use an array, so we could wrap this in an array here. As you can see, it still works. Can also remove one, and it works again. Obviously, these can be added dynamically within your application codes, so you can add or remove classes here from that array.

[01:12] A third possibility which we have is to use an object. The main advantage of using an object is that we get another value here. Being a key value kind of data structure, we can add here Boolean conditions.

[01:31] Let's wrap this a bit nicer here so that we get a better sight of the variables. We'll add here a little bit of condition, and let's add false for the highlight, and let's add true for the strike. As you can see, based on the outcome of these values, the classes get applied or not.

[01:54] These are all CSS classes, as such, they belong more to the HTML part up here rather than to the JavaScript part. Most often, you see them directly in line. Let's reformat them again. Now let's cut them out. Let's remove that CSS part here and go to our ng-class definition again, and we paste it in again. Let's save, and it still works.

[02:21] As a next step, you usually bind those variables here, which obviously are not hard-coded, but they are directly bound to some variables which are defined inside here, so in your JavaScript part. Let's add here isBold. Great.

[02:35] Obviously, we need to bind them, isBold, isHighlight, and isStrike. To get a better effect here, let's add some check boxes. Great. As you can see, the check boxes are two-way data-bound to our variables, which we have defined here below.

[03:05] In turn, those variables are data-bound via that ng-class directive here. Now we can then activate or deactivate different kind of styles, and even multiple styles.