Angular Class Binding

Angular Class Binding

In this article, I am going to discuss the Angular Class binding with examples. We are going to work with the same example that we have been working with so far of this article series. Please read the following articles before proceeding to this article.

Angular Interpolation

The Property Binding

HTML Attribute VS DOM Property

Attribute Binding in Angular

Let’s first include the following CSS classes in the styles.css file.

.boldClass{
    font-weight:bold;
}

.italicsClass{
    font-style:italic;
}

.colorClass{
    color:red;
}

Then add a reference to this styles.css file in the index.html file which is our host page.

In app.component.ts file, let’s include a button element as well as we need to set the class attribute of the button element to ‘colorClass‘ as shown below.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<div>
                  <button class='colorClass'>My Button</button>
              </div>`
})

export class AppComponent {
}

Now run the application and you will see that the ‘colorClass’ is added to the button element as shown below.

Angular Class Binding
Replace all the existing CSS classes with one or more classes

Modify the code in app.component.ts as shown below.

Here, we have introduced a property ‘ClassesToApply‘ in 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

This will replace the existing CSS classes of the button with classes specified in the class binding

Angular Class Binding

Now run the application and see the output as shown below.

Angular Class Binding

From the above output, it clearly shows that the ‘colorClass’ is removed and these classes (italicsClass & boldClass) are added to the button element.

Adding or removing a single class:

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

The following example adds boldClass to the button element. Notice it does not remove the existing colorClass already added using the class attribute. If you change ApplyBoldClass property to false or remove the property altogether from the AppComponent class, CSS class boldClass is not added to the button element.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<div>
                  <button class='colorClass' [class.boldClass]='ApplyBoldClass'>My Button</button>
              </div>`
})

export class AppComponent {
    ApplyBoldClass: boolean = true;
}

With class binding, we can also use the “!” symbol. Notice in the example below ApplyBoldClass is set to false. Since we have used the “!” symbol in the class binding the class is added as expected.

Angular Class Binding

Lets us see how we can also remove an existing class that is already applied.

Consider the following example. Notice we have 3 classes (colorClass, boldClass & italicsClass) added to the button element using the class attribute. The class binding removes the boldClass.

Angular Class Binding To add or remove multiple classes

If we want to add or remove multiple classes then we need to use ngClass directive as shown in the example below.

Notice the colorClass is added using the class attribute

ngClass is bind to AddCSSClasses() method of the AppComponent class

AddCSSClasses() method returns an object with 2 key/value pairs. The key is a CSS class name. The value can be true or false. True to add the class and false to remove the class.

Since both the keys (boldClass & italicsClass) are set to true, both classes will be added to the button element

The let is a new type of variable declaration in JavaScript.

let is similar to var in some respects but allows us to avoid some of the common gotchas that we run into when using var. 

The differences between let and var are beyond the scope of this session. For our example, var also works fine.

As TypeScript is a superset of JavaScript, it supports let

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<div>
                  <button class='colorClass' [ngClass]='AddCSSClasses()'>My Button</button>
              </div>`
})

export class AppComponent {
    ApplyBoldClass: boolean = true;
    ApplyItalicsClass: boolean = true;

    AddCSSClasses() {
        let Cssclasses = {
            boldClass: this.ApplyBoldClass,
            italicsClass: this.ApplyItalicsClass
        };

        return Cssclasses;
    }
}

We have included our CSS classes in an external stylesheet that is styles.css. Please note we can also include these classes in the styles property instead of a separate stylesheet as shown below.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<div>
                  <button class='colorClass' [ngClass]='AddCSSClasses()'>My Button</button>
              </div>`,
    styles: [`
                .boldClass{
                    font-weight:bold;
                }

                .italicsClass{
                    font-style:italic;
                }

                .colorClass{
                    color:red;
                }
             `]
})

export class AppComponent {
    ApplyBoldClass: boolean = true;
    ApplyItalicsClass: boolean = true;

    AddCSSClasses() {
        let Cssclasses = {
            boldClass: this.ApplyBoldClass,
            italicsClass: this.ApplyItalicsClass
        };

        return Cssclasses;
    }
}

In the next article, I will discuss the Angular Style Binding with examples.

SUMMARY:

In this article, I try to explain Angular Class Binding with some examples. I hope this article will help you with your need. 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 *