dynamic and conditional CSS classes with ngClass angular 9

Angular 9 : Dynamic and conditional CSS classes with ngClass

This tutorial guides you on how to apply dynamic and conditional CSS classes with ngClass in Angular 9. NgClass is a built-in directive which can be used to add and remove CSS classes dynamically and conditionally on an HTML element.

Dynamic and conditional CSS classes with ngClass : Angular 9

We have seen examples for NgStyle and NgIf. And NgClass directive is related to NgStyle, which will allow you to update styles of the containing HTML element dynamically.

The below code sneppet is from NgStyle example which will add or remove styles dynamically.

<p *ngIf="isServerRefreshed; else noServerRefresh" 
   [ngStyle]="{backgroundColor: getColor()}"> Server Refreshed! Name of server is: {{serverName}}</p>
<ng-template #noServerRefresh> 
    <p [ngStyle]="{backgroundColor: getColor()}">No Server was Refreshed!</p>
</ng-template>

Here “backgroundColor” is the key or style name and getColor() is the styleExpression which will be evaluated and the style results will be applied to the containing HTML element. And this method needs to be implemented like below in your component class.

getColor(){
    return this.isServerRefreshed === true ? 'green' : 'yellow';
}

You might have seen in this NgStyle example the output looks like below.

apply css style attribute dynamically ngstyle angular 9

Now, let’s try to do some modifications to NgStyle example, so that we can use conditional CSS classes with ngClass to add or remove CSS classes dynamically.

First, let us also add ngClass along with ngStyle in the template as shown below.

<p *ngIf="isServerRefreshed; else noServerRefresh" 
   [ngStyle]="{backgroundColor: getColor()}"
   [ngClass]="{refreshed: getColor() === 'green'}"> Server Refreshed! Name of server is: {{serverName}}</p>
<ng-template #noServerRefresh> 
    <p [ngStyle]="{backgroundColor: getColor()}">No Server was Refreshed!</p>
</ng-template>

Here ngStyle allows us to change the CSS style alone. Whereas, ngClass allows us to dynamically add or remove CSS classes.

The below is the example syntax for NgClass directive to apply CSS classes to HTML elements dynamically.

[ngClass]="{key: cssClassConditionalExpression}"

We will have to use property binding on the NgClass directive. Therefore, we use square brackets “[ ]” around the ngClass directive to indicate that we wanted to bind to some property on this directive. The key is the class name and the value is the cssClassConditionalExpression i.e., only if getColor() returns ‘green‘ then it will attach the css class otherwise it won’t.

Then, you need to add styles in the component class (typescript file) as shown below.

@Component({	
	selector:'app-server',
	templateUrl:'./server.component.html',
	styles:[`
		.refreshed {
			color: white;
		}  	
    `]
})

Here we added a style class (.refreshed) which colors the text with white color.

Example: Conditional CSS with ngClass – Angular 9

Now, let’s see the demo with ngClass implementation. To try this example, your component template file should have the following code.

server.component.html

<p>{{'Server'}} with ID {{serverId}} is {{getServerStatus()}}</p>

<p *ngIf="isServerRefreshed; else noServerRefresh" 
   [ngStyle]="{backgroundColor: getColor()}"
   [ngClass]="{refreshed: getColor() === 'green'}"> Server Refreshed! Name of server is: {{serverName}}</p>
<ng-template #noServerRefresh> 
    <p [ngStyle]="{backgroundColor: getColor()}">No Server was Refreshed!</p>
</ng-template>

<button class="btn btn-primary" [disabled]="!isRefreshAllowed" (click)="onRefresh()">Refresh</button>

And your component class (typescript file) should have the following code.

server.component.ts

import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';

@Component({
	
	selector:'app-server',
	templateUrl:'./server.component.html'
})

export class ServerComponent implements OnInit {


	isRefreshAllowed = false;
	serverId: number = 10;
	serverStatus: string = 'offline'; 
	serverName = 'Server 10';
	isServerRefreshed = false;
 
	constructor() {

		setTimeout(() => {
			this.isRefreshAllowed = true;
		}, 3000); 		
	} 

	ngOnInit() {
	  
	   console.log('Component has been initialized');
	   
	}

	getServerStatus(){
		
		return this.serverStatus;
	}

	onRefresh(){
		
		this.isServerRefreshed = true;
	
	}

	getColor(){
		
		return this.isServerRefreshed === true ? 'green' : 'yellow';
	}

}

Then, your root component (App Component) should have the following code.

app.component.html

<div class="container">
	<div class="row">
		<div class="col-xs-12">			
			<h3>My First Component !</h3> 
			<hr>			
			<app-server></app-server>			
		</div>
	</div>
</div>

Finally, when you run the angular application you should see the following output.

Output

dynamic and conditional CSS classes with ngClass angular 9

In Step 1 & Step 2 the paragraph content “No Server was Refreshed” is applied with CSS style results (yellow background color) based on the evaluation of the styleExpression (getColor()). And when user clicks “Refresh” button the return statement ( this.isServerRefreshed === true ? ‘green’ : ‘yellow’; ) in the getColor() method returns ‘green‘.

And according to the syntax for ngClass [ngClass]=”{refreshed: getColor() === ‘green’}” , in the cssClassConditionExpression(value) only if getColor() returns ‘green‘ then it will attach the css class “.refreshed” (key) otherwise it won’t. This css style class colors the text with white color as shown.

That’s it, the CSS Class has been applied dynamically and conditionally using ngClass directive.

Also See:

References:

Leave a Reply

avatar
  Subscribe  
Notify of