In this blog post, we’ll explore Angular ngClass conditional class Example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply classes and style to elements. We’ll discuss how to use the angular ngClass
conditionally to achieve this.
Conditional class in angular using ngClass
let’s take a look at how to use the ngClass directive. The ngClass directive allows you to dynamically add or remove CSS classes based on certain conditions. For example, let’s say we have a component with two CSS classes: .red and .blue. We can use the ngClass conditional directive to conditionally add or remove these classes like so:
<a [ngClass]="{'red':true, 'blue':false}">
This div will have the class "red" and not the class "blue".> </a>
let understand Angular ngClass conditional class with Example
Step 1 : Create an angular app
First step is to setup an angular app using below command
ng new example-app
Step 2: Create a Component
Create a component and a method
ng g c hello-world
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
dyanmicCssObject:any ={'margin':'20px','color':'blue'};
changeColor:boolean=false;
constructor() {
}
onChangeColor() {
this.changeColor = !this.changeColor;
}
ngOnInit() {}
}
Here we used to
method to change the colorchangeColor
Step 3 : Create template and add html
Now, add simple html template with input field
<h2>Angular Dynamic Style CSS with Example- Readerstacks.com</h2>
<div [ngStyle]="dyanmicCssObject"> Dynamic Object COlor </div>
<div [ngStyle]="{'background-color': ? 'red' : 'white'}"> Dynamic varibale COlor</div>
<a href="#" (click)='onChangeColor()'>Change</a>