Angular has a lot of built-in directives like ngClass, ngStyle, and ngModel. These directives are non-structure directives or attribute directives, mostly used to change DOM element appearance.
Angular also has structure directives like *ngIf, *ngFor, *ngSwitch . These directives manipulate the DOM element by adding or removing elements based on condition.
What is Angular ngClass directive
This directive allows us to change the appearance of DOM elements by adding or removing CSS classes on elements in the template of the component.
This directive is a more flexible alternative to the standard and special property bindings. It behaves differently based on the type of data that is returned by the expression and allows encapsulating class names in a TypeScript object.
Angular ngClass directive syntax
The argument of ngClass is an object that contains pairs of a CSS class name and an expression. The CSS class name is added to the target DOM element if the expression is true. We can add single or multiple CSS classes name on this attribute based on condition expression.
<div ngClass="container">...</div>
<div [ngClass]="{'container': true}">
ngClass condition
</span>,
<any-element [ngClass]="{selected: isSelected}">
...
</any-element>
OR
<any-element [ngClass]="{selected: isSelected, disabled: isDisabled}">
...
</any-element>
In this directive, we can pass string, object, array, and method as an expression in it.
Angular ngClass example
We will have a few examples of this directive. The first example is with one condition and we are setting font color white and background: red for all even numbers using ngClass. The numbers array contain a list of number and we can iterate it using ngFor and apply the background color red to all even number in an array.
<p *ngFor="let number of numbers" [ngClass]="{'even': number % 2 === 0}">
{{ number }}
</p>
ngClass with two conditions
We can also pass two conditions in this attribute, isSelected and isDisabled are conditions based on the condition we will select our class name selected and disabled.
<any-element [ngClass]="{selected: isSelected, disabled: isDisabled}">
...
</any-element>
We can use method in ngClass directive expression as
We can also pass the method on this attribute, this method will return a boolean true or false.
<div [ngClass]="{'open': isOpen(), 'close': !isOpen()}">
...
</div>
Object contain CSS Classname in ngClass Atrribute
For example, three we can pass an object in this attribute, let first define our class object with its properties to enable and disable its CSS value.
Let’s add code to toggle the background on or off to this div element. Here we have added cssClasses object as an expression.
<div ngClass="container">
<div [ngClass]="cssClasses">
Welcome to ngClass example
</div>
<button (click)="changeCss()">
Toggle Background
</button>
</div>
In our component typescript, we can add value for our cssClasses as below.
...
export class AppComponent {
cssClasses: { [key: string]: boolean } = {
'addBorder': true,
'addBgColor': true,
}
changeCss() {
this.cssClasses.addBgColor = !this.cssClasses.addBgColor;
}
}
In our CSS stylesheet component add the following CSS value.
.container {
margin-left: 20px;
.addBorder {
margin: 10px;
padding: 20px;
width: 200px;
border: 1px solid black;
}
.addBgColor {
background-color: springgreen;
}
}
In ngClass example four, we have passed objects from typescript to this attribute directives. We can also pass objects directly into ngClass to set the font color of data.
<table>
<tr *ngFor="let country of countries; index as i">
<td>{{ i }}</td>
<td>
<img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="mr-2"
style="width: 20px">
{{ country.name }}
</td>
<td>{{ country.area | number }}</td>
<td [ngClass]="{
'blue':country.name === 'France',
'yellow':country.name === 'Germany',
'orange':country.name === 'India',
'bold':true
}">
{{ country.population | number }}
</td>
</tr>
</table>
In our CSS style component file let’s add style.
table {
width: 100%;
.rowLine {
border-bottom: 1px solid grey;
}
.blue {
color: blue;
}
.orange {
color: orange;
}
.yellow {
color: yellow;
}
.bold {
font-weight: bolder;
}
}
In our component typescript file, let’s add data for countries array object as below.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
countries = [
{
"name": "France",
"flag": "c/c3/Flag_of_France.svg",
"area": 640679,
"population": 64979548,
"description": "France, the largest country in Western Europe, has long been a gateway between the continent's northern and southern regions."
},
{
"name": "Germany",
"flag": "b/ba/Flag_of_Germany.svg",
"area": 357114,
"population": 82114224,
"description": "Germany is a country located in the heart of Western Europe."
},
{
"name": "India",
"flag": "4/41/Flag_of_India.svg",
"area": 3287263,
"population": 1324171354,
"description": "India (Hindi: Bhārat), officially the Republic of India (Hindi: Bhārat Gaṇarājya) is a country in South Asia."
}
];
}
Conclusion
We had learned and demonstrated a few examples of how to use the ngClass attribute, it is more flexible than property binding.
Related posts
- How to implement the Angular ngStyle directive with an example?
- An angular directive in detail with an example
- Angular dynamically adds and removes CSS Classes using ngClass | custom directive
- How to pass data in the angular route component?
- Sharing data between Angular Component
- How to use to implement HighCharts Angular?