Monday, April 27, 2020

Angular Class Binding With Examples

In this post we’ll discuss another one-way binding known as Angular class binding. Using class binding you can add and remove CSS classes dynamically from an element's class attribute.

Angular class binding syntax

Syntax of class binding is similar to property binding, square brackets are used for class binding too. To create a class binding, start with the prefix class followed by a dot (.) and the name of the CSS class.

[class.CSS_CLASS]="isRequired"

Here CSS class CSS_CLASS is added when the bound expression is truthy (i.e. isRequired is true), and it removes the class when the expression is falsy (i.e. isRequired is false).

Adding multiple CSS classes

Angular class binding can also be done to multiple classes by using a generic [class] binding without the dot (for example, [class]="classExpr").

The expression can be a space-delimited string of class names. For example

[class]="my-class-1 my-class-2 my-class-3"

You can format it as an object (object, Array, Map, Set, etc) with class names as the keys and truthy/falsy expressions as the values.

As key/value pair- [class]="{my-class-1: true, my-class-2: false}”

As an array - [class]=['my-class-1', 'my-class-2']

Angular class binding examples

1. In the example we want to display sales figures region wise and want to highlight the sales figures which are good in different color and the sales figures which are not satisfactory in different color. For that styling class binding is used with the condition on the sales figures.

region.model.ts

Model class with fields.

export class Region {
    region : string;
    regionalManager : string;
    sales : number;
    constructor(region: string, regionalManager : string, sales : number) {
        this.region = region;
        this.regionalManager = regionalManager;
        this.sales  = sales;
    }
}

Component class

Component used Region model so that class is imported. There is an array of type Region in which instances of Region are stored.

import { 
    Component
 } from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
    regions: Region[];
 
    constructor(){
        //Adding Region instances to regions array
        this.regions = [new Region('East', 'Jack', 145),
                       new Region('West', 'Jerry', 225),
                       new Region('North', 'Lisa', 300),
                       new Region('South', 'Randy', 175)] ;
    }
}

CSS Class

.domore {
    background-color: #d41e2e;
    color: #ffffff;
  }
.satisfactory {
    background-color:green;
    color: #ffffff;
}

Template

<div class="container">
    <table class="table table-sm table-bordered m-t-4">
        <tr>
            <th>Region</th>
            <th>Manager</th>
            <th>Sales (in millions)</th>
        </tr>
        <tr *ngFor="let region of regions" [class.domore] = "region.sales < 150"
            [class.satisfactory] = "region.sales > 250">
            <td>{{region.region}}</td>
            <td>{{region.regionalManager}}</td>
            <td>{{region.sales}}</td>
        </tr>
    </table>
</div>

With the <tr> element there are two class bindings

 [class.domore] = "region.sales < 150"
 [class.satisfactory] = "region.sales > 250"

When sales is less than 150 domore CSS class is added, when sales is greater than 250 then satisfactory CSS class is added.

class binding example

2. In this example we’ll see how to do class binding for multiple CSS classes. To demonstrate that one more CSS class is added.

CSS

.domore {
    background-color: #d41e2e;
    color: #ffffff;
  }
.satisfactory {
    background-color:green;
    color: #ffffff;
}

.brd {
    border: 2px solid black;
}

Component

import { 
    Component
 } from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
    regions: Region[];
 
    constructor(){
        //Adding Region instances to regions array
        this.regions = [new Region('East', 'Jack', 145),
                    new Region('West', 'Jerry', 225),
                    new Region('North', 'Lisa', 300),
                    new Region('South', 'Randy', 175)] ;
    }

    getCssClasses(sales : Number){
        if(sales < 150){
            return "domore brd";
        }else if(sales > 250){
            return "satisfactory brd";
        }
    }
}

In the component a method getCssClasses() is added in which sales figures are passed as argument. Based on the condition two CSS classes are passed.

Template

<div class="container">
    <table class="table table-sm table-bordered m-t-4">
        <tr>
            <th>Region</th>
            <th>Manager</th>
            <th>Sales (in millions)</th>
        </tr>
        <tr *ngFor="let region of regions" [class] = "getCssClasses(region.sales)">
            <td>{{region.region}}</td>
            <td>{{region.regionalManager}}</td>
            <td>{{region.sales}}</td>
        </tr>
    </table>
</div>

In the <tr> element now we have generic class binding is used with a bound method. From the method space delimited string of CSS class names is returned.

Angular Class Binding

That's all for this topic Angular Class Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Style Binding With Examples
  2. Angular Attribute Binding With Examples
  3. Angular ngClass Directive With Examples
  4. How to Install Node.js and NPM in Windows

You may also like-

  1. Angular Disable Button Example
  2. Angular @Component Decorator
  3. JVM Run-Time Data Areas - Java Memory Allocation
  4. Adding Tomcat Server to Eclipse
  5. Java Reflection API Tutorial
  6. static Reference to The Non-static Method or Field Error
  7. String Slicing in Python
  8. Spring Transaction Attributes - Propagation And Isolation Level Settings