How to add Conditional Class in Angular 14
Prerequisites
Before starting an Angular project, you should have the following prerequisites installed on your system
- Node.js
- npm (Node Package Manager)
- Angular CLI
Once you have installed these prerequisites, you are ready to create your first Angular application.
What is the ngClass expression or directive in 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.
How to use ngclass with condition?
Angular provides several ways to add classes conditionally.
- ngClass Directive - Add a dynamic CSS class based on the simple condition
- style binding - Add a dynamic CSS class based on the complex conditions
- Host binding -
- Renderer2
- ngStyle Directive - Add multiple CSS classes using ngClass
- Call a method within ngClass
ngClass Directive
In your component's HTML template the ngClass directive to be applied to the element property/attribute. This expression can be a single class name, an array of class names, or an object with class-name key-value pairs.
Here is an example of how to use ngClass directive to add a dynamic class "ngClass" based on a boolean variable "isActive" value:
For example of single class name expression, 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;
result:boolean = false;
export class AppComponent {
// component logic here
}
.active {
background-color: rgb(12, 110, 12);
color: rgb(238, 237, 237);
}
The class "active" will be added if isActive variable is true
<div [ngClass]="{ 'active': isActive }">
</div>
Style Binding
Angular providing a flexible and powerful way to handle styling in component's template. Style Binding is very similar to the traditional way of apply inline styles to elements in HTML.
In your component's HTML template the style attribute is used to define the dynamic styles.
<div [style.background-color]="backgroundColor">
<div class="container">
HTML template here
</div>
</div>
In your app.component.ts:
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
// variable
backgroundColor:string = "red";
export class AppComponent {
// component logic here
}
Host Binding
In your app.component.ts:
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
@HostBinding('class.my-class') hasClass: boolean = true;
@HostBinding('style.background-color') backgroundColor: string = 'blue';
// component logic here
}
Renderer2
ngStyle Directive
Call a method within ngClass
this.result=true;
getClass(status: boolean) {
return {
'sucess': resulution == true,
'error': resulution == false
}
}
<div [ngClass]="getClass(result)">
// add HTML element here
</div>
Example
To demonstrate this let’s try out a full example. We have created few CSS class below which we will use them in diffrent usecase, such "add dynamic calss with a condition" and "add css class with multiple conditions".
.error {
background-color: #df3d3d; // red
color: #eeeded;
}
.success {
background-color: #089708; // green
color: #eeeded
}
Use Case 1 : Add dynamic CSS class based on the simple condition.
In this use case we will try to change the background and text color of div.
this.result=true;
The value of result variable is true so thet background color of the element will be green.
<div [ngClass]="{ 'success': result }">
// display message here
</div>
Use Case 2 : How to Use Angular ngClass with multiple conditions
In this use case we will try to change the background based upon HTTP Api success response.
- on error - set background color Red.
- on success - set background color Green.
this.productService.updateProduct(this.form.value).subscribe(
(data :any) => {
if (value.statusCode === 200) {
this.result=true; // success response
}
},
(error:any)=>{
this.result=false; // error response
}
});
<div [ngClass]="{ result ?'success':'error' }">
</div>
Use Case 3 : Add multiple CSS classes using ngClass.
The class "active" and "success" will be added if result variable is true.
<div [ngClass]="{ 'active success': result }">
// add HTML element here
</div>
or we can use in this way also
<div [ngClass]="result? 'active success' : 'active error'">
// add HTML element here
</div>
Conclusion
Thank you for reading this article. Hopefully now you know How to add Conditional Class in Angular 14.