Angular Class Binding

Angular Class Binding with Examples

In this article, I am going to discuss the Angular Class Binding with examples. Please read our previous article where we discussed Angular Attribute Binding in detail. At the end of this article, you will understand what exactly Angular Class Binding is and when and how to use Class Binding in Angular Application.

What is Angular Class Binding?

The Angular Class Binding is basically used to add or remove classes to and from the HTML elements. It is also possible in Angular to add CSS Classes conditionally to an element, which will create the dynamically styled elements and this is possible because of Angular Class Binding.

Understanding Class Binding in Angular Application:

Let us understand Angular Class Binding with an example. First, open the styles.css file and then copy and paste the following code in it. You can find styles.css file within the src folder of your project.

.boldClass{
    font-weight:bold;
}

.italicClass{
    font-style:italic;
}

.colorClass{
    color:red;
}

Note: Please make sure to have a reference to this styles.css file in the index.html file which is your host page as shown in the below image.

Angular Class Binding with Examples

Modifying app.component.ts file:

Modify the app.component.ts file as shown below. Here we are just adding a button element as well as we also set the class attribute of the button element to ‘colorClass‘. If you remember this colorClass class is defined in the styles.css file.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                  <button class='colorClass'>Click Me</button>
              </div>`

})
export class AppComponent {
}

Now run the application and you should see the ‘colorClass’ is applied to the button element as expected as shown in the below image.

without using Class Binding in Angular

Using Class Binding in Angular:

Let us see how to use class binding in angular. To do so, first, modify the app.component.ts file as shown below. Here, as you can see, we have created a property called ClassesToApply in the AppComponent class. We have also specified the class binding for the button element. The word ‘class‘ is in a pair of square brackets and it is bound to the property ‘ClassesToApply‘.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                  <button [class] = 'ClassesToApply' >Click Me</button>
              </div>`
})
export class AppComponent {
  ClassesToApply : string = 'italicClass boldClass';
}

Once you save changes, then you will get the following output. Here you can see the button is italic as well as bold.

Using Class Binding in Angular

If you want then you can also combine both class binding with the normal class as shown in the below example.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                  <button class='colorClass' [class] = 'ClassesToApply' >Click Me</button>
              </div>`
})
export class AppComponent {
  ClassesToApply : string = 'italicClass boldClass';
}

Now you should get the button with all the three CSS classes like the color red, bold and italic as shown in the below image.

Using both Class Attribute and Class Binding in Angular Application

Adding or removing a single class:

Suppose you want to add or remove a single class, then you need to include use the prefix ‘class’ within a pair of square brackets and followed by a DOT (.) and the name of the class that you want to add or remove.

The following example adds the boldClass to the button element. Notice it does not remove the existing colorClass which is added using the class attribute.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                <button class='colorClass' [class.boldClass]='ApplyBoldClass'>Click Me</button>
              </div>`
})
export class AppComponent {
  ApplyBoldClass: boolean = true;
}

Now, if run the application, then you should see the button with red color and bold. If you set the ApplyBoldClass property value to false or remove the property altogether from the AppComponent class, then the CSS class i.e. boldClass will not be added to the button element. In the following example, we have set the ApplyBoldClass property value to false and when you browse the application, you will see the button without bold.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                <button class='colorClass' [class.boldClass]='ApplyBoldClass'>Click Me</button>
              </div>`
})
export class AppComponent {
  ApplyBoldClass: boolean = false;
}
Angular Class Binding using “!” symbol:

In Angular Class Binding, it is also possible to use the “!” symbol. Notice in the following example, we have set ApplyBoldClass property value to false. As we use the “!” symbol in the class binding, the class is going to be added to the button element.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                <button class='colorClass' [class.boldClass]='!ApplyBoldClass'>Click Me</button>
              </div>`
})
export class AppComponent {
  ApplyBoldClass: boolean = false;
}

Now, if you run the application, then you should the bold class is applied to the button element as expected.

How to remove an existing class using Class Binding in Angular?

Let us understand this with an example i.e. how to remove an existing class that is already applied by using Angular Class Binding. Consider the below example. Here we have 3 classes (colorClass, boldClass, and italicsClass) added to the button element using the class attribute. Then the class binding removes the boldClass.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                <button class='colorClass italicClass boldClass' [class.boldClass]='ApplyBoldClass'>Click Me</button>
              </div>`
})
export class AppComponent {
  ApplyBoldClass: boolean = false;
}

That’s fine. But if we want to add or remove multiple classes then how we can do this?

Add or Remove multiple classes in Angular:

In order to add or remove multiple style classes in angular, the angular framework provides one directive called ngClass directive which you can use to remove or add multiple classes as shown in the below example. What is a directive and what are the different types of directives that we will discuss in detail in our upcoming articles. For now, let us see how to use the ngClass directive to add or remove multiple classes.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `<div>
                <button class='colorClass' [ngClass]='AddCSSClasses()'>Click Me</button>
              </div>`

})
export class AppComponent {
    ApplyBoldClass: boolean = true;
    ApplyItalicsClass: boolean = true;
    AddCSSClasses() {
        let Cssclasses = {
            boldClass: this.ApplyBoldClass,
            italicsClass: this.ApplyItalicsClass
        };
        return Cssclasses;
    }
}
What we are doing here?
  1. Here the colorClass is added using the class attribute
  2. The ngClass directive is bind to the AddCSSClasses() method of the AppComponent class
  3. Here, AddCSSClasses() is method that returns an object with 2 key/value pairs. The key is the CSS class name and the value can be true or false. If the value is true then it will add the class and when the value is False then it will remove the class.
  4. Since both the keys (boldClass & italicsClass) are set to true, both classes will be added to the button element
  5. The let is a new type of variable declaration in JavaScript. let is similar to var in some respects. In our upcoming article, we will discuss let and var in detail as well as discuss the differences between them. For this example, you can also use var and it should work.

In the next article, I am going to discuss Angular Style Binding with examples. Here, in this article, I try to explain Angular Class Binding with some examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *