HTML binding in Angular 14
Prerequisites
- An integrated development environment like VS Code.
- Node version 16.0 installed on your machine.
- Angular CLI version 8.0 or higher
- The latest version of Angular
- Create new project How to create angular project angular
Angular has built-in directive ngClass,To add a conditional class in Angular component, we can use the directive ngClass. This directive allows you to dynamically add or remove CSS classes based on the candition.
Angular provides several ways to add classes conditionally.
Here is an example of how to use directive ngClass to add a conditional class '' based on a boolean variable:
For example, let's create a boolean variable called isActive in your app.component.ts:
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
// variable
isActive:boolean = true;
status:string='';
export class AppComponent {
// component logic here
}
I have created few css active,error and success classes below which we will use them in diffrent usecase, such "add dynamic calss with a condition" and "add css class with multiple conditions".
.active {
background-color: rgb(12, 110, 12);
color: rgb(238, 237, 237);
}
.error {
background-color: rgb(223, 61, 61);
color: rgb(238, 237, 237);
}
.success {
background-color: rgb(8, 151, 8);
color: rgb(238, 237, 237);
}
Example
Use Case 1 : Hide and display HTML element based on the 'isActive' variable value.
- hide element if 'isActive' variable value is false.
- display elment if 'isActive ' variable value is true.
<div [ngClass]="{ 'active': isActive }">
The class "active" will be added if isActive variable is true
</div>
or we can use in this way also
<div [class.pending]="active === 'true'">
The class "active" will be added if isActive variable is true
</div>
Use Case 2 : Change HTML element background color based on the variable value.
- set background color 'red' of element if 'isActive' variable value is false.
- set background color 'green' of element if 'isActive' variable value is true.
<div [ngClass]="{ 'active': isActive }">
The class "active" will be added if isActive variable is true
</div>
or we can use in this way also
<div [class.pending]="active === 'true'">
The class "active" will be added if isActive variable is true
</div>
How to Use Angular ngClass with multiple conditions
<div [ngClass]="{'error': status=='error','success' : status=='success' }">
The class "active" will be added if isActive variable is true
</div>
or we can use in this way also
<div [ngClass]="status=='error' ? 'error':'success'">
The class "active" will be added if isActive variable is true
</div>
Conclusion
Thank you for reading this article. Hopefully now you know HTML binding in Angular 14.