Angular Directives NgClass And NgStyle - How To Change The Style Of An HTML Element Conditionally

Introduction

The Directive is the class that adds additional behaviour to the HTML element in the Angular application. Angular provides many built-in directives that help us to manage the style, lists, and change the DOM layout. In this article, I will talk about the NgClass and NgStyle built-in attribute directives that help us to manage the style based on condition.

Adding and removing style classes with NgClass

The NgClass directive binds multiple CSS classes to the HTML element dynamically. It assigned/ removed the class value to the element based on the condition. You can use either the expression or method with NgClass directive.

Using Expression

You cannot write if condition with the ngClass directive but you need to use the ternary operator as this is an expression.

//Syntax
[ngClass]="Condition ? 'apply class if true' : 'apply class if false'"

In the following example, based on the radio button selection either "green" or "blue" class is applied to the div element.

//ng-class-example.component.html <p> Using Expression</p>
<input id="green" type="radio" value="g" name="color" (change)="handleChange('g')" [(ngModel)]="selectedValue">
<label class="custom-control-label" for="green">Green</label>
<span style="padding-right:25px;"></span>
<input id="blue" type="radio" value="b" name="color" (change)="handleChange('b')" [(ngModel)]="selectedValue">
<label class="custom-control-label" for="blue">Blue</label>
<br>
<br>
<div [ngClass]="isGreen ? 'green' : 'blue'"></div>
//ng-class-example.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-ng-class-example',
    templateUrl: './ng-class-example.component.html',
    styleUrls: ['./ng-class-example.component.css']
})
export class NgClassExampleComponent implements OnInit {
    isGreen: boolean = true;
    selectedValue: string = 'g';
    selectedInputValue: number = 0;
    constructor() {}
    ngOnInit(): void {}
    handleChange(value: string) {
        if (value == 'g') {
            this.isGreen = true;
        } else {
            this.isGreen = false;
        }
    }
}
// This is just a sample script. Paste your real code (javascript or HTML) here.
if ('this_is' == /an_example/) {
    of_beautifier();
} else {
    var a = b ? (c % d) : e[f];
}
//ng-class-example.component.css
.green {
    background-color: green;
    width: 100px;
    height: 100px;
}
.blue {
    background-color: blue;
    width: 100px;
    height: 100px;
}

Output

Using Method or Function

You can apply CSS class through method in case of complex conditions. For example, based on user input, if you want to set CSS class then you can use it this way. 

In the following example, if user enters value 0-50 then 'low' class is applied, if user enters value 51-80 then 'medium' class is applied else 'high' class is applied to the div element.

//ng-class-example.component.html
<p> Using Method</p>
Enter your Value<input type="number" [(ngModel)]="selectedInputValue" min="0" max="100">
<br>
<br>
<div [ngClass]="getClassValue()"></div>
//ng-class-example.component.ts
getClassValue() {
  if (this.selectedInputValue >= 0 && this.selectedInputValue <= 50) {
    return 'low';
  } else if (this.selectedInputValue > 50 && this.selectedInputValue <= 80) {
    return 'medium';
  } else {
    return 'high'
  }
}
//ng-class-example.component.css
.low {
    background-color: red;
    width: 100px;
    height: 100px;
}
.medium {
    background-color: yellow;
    width: 100px;
    height: 100px;
}
.high {
    background-color: green;
    width: 100px;
    height: 100px;
}

Output

Due to the change detection mechanism works in Angular, the method/fuction may call multiple times even when it is not necessary. You can also achieve the same result without using the function.

//ng-class-example.component.html
<p> Complex condition without Method</p>

<div [ngClass]="{ low: selectedInputValue >= 0 && selectedInputValue <=50, medium: selectedInputValue > 50 && selectedInputValue <= 80, high: selectedInputValue > 80}"></div>

NgStyle

The NgStyle directive allows you to set style property of the DOM Element. You can assign style to the element like string and you can also add condition inside the string.

In the following example, based on checkbox check, "font-style" and "font-weight" CSS are applied to the span element.

//ng-style-example.component.html
<p>Simple Example</p>
<input type="checkbox" [(ngModel)]="isBold"/>Bold <br>
<input type="checkbox" [(ngModel)]="isItalic"/>Italic
<span [ngStyle] = "{'font-style':isItalic? 'italic' : 'normal', 'font-weight':isBold? 'bold' : 'normal' }">
    This is My Test String
</span>

Output

Alternatively, you can also retrieve the style using the method. 

//ng-style-example.component.html
<p>Get element style using Method</p>
<span [ngStyle] = "getElementStyle()">
    This is My Test String
</span>
//ng-style-example.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-ng-style-example',
    templateUrl: './ng-style-example.component.html',
    styleUrls: ['./ng-style-example.component.css']
})
export class NgStyleExampleComponent implements OnInit {
    isBold: boolean = false;
    isItalic: boolean = false;
    constructor() {}
    ngOnInit(): void {}
    getElementStyle() {
        var style = {
            'font-style': this.isItalic ? 'italic' : 'normal',
            'font-weight': this.isBold ? 'bold' : 'normal',
        };
        return style;
    }
}

Summary

The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.