apply css style attribute dynamically ngstyle angular 9

Apply CSS style attribute dynamically with ngStyle : Angular 9

This tutorial guides you on how to apply CSS style attribute dynamically with ngStyle in Angular 9. Unlike structural directives (NgIf), attribute directives (NgStyle) don’t add or remove elements. But they can be used to style elements dynamically.

Apply CSS style attribute dynamically with ngStyle : Angular 9

As mentioned, ngStyle directive is an attribute directive that can be used to update styles of the containing HTML element dynamically. The below is the example syntax for NgStyle directive to style elements dynamically.

[ngStyle]="{key: styleExpression}"

We will have to use property binding on the NgStyle directive. Therefore, we use square brackets “[ ]” around the ngStyle directive to indicate that we wanted to bind to some property on this directive.

And on the right hand side of the equal sign you can set one ore more style properties, specified as colon separated key-value pairs backgroundColor: ‘yellow’ . The key is the style name and the value is the style expression that needs to be evaluated.

Note, if the result of styleExpression evaluation is null, then the corresponding style is removed.

Example – Styling elements dynamically with [ngStyle]

Now let’s see how to use ngStyle attribute directive in the angular application template. In the below example, we have used ngStyle directive along with structural directive (ngIf). Here [ngStyle]=”{backgroundColor: ‘getColor()’}”  is added to the paragraph tag of the angular template.

<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';
}

Now, let’s see the demo with ngStyle 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>

<!--[ngStyle] demo-->
<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>

<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

apply css style attribute dynamically ngstyle 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‘.

That’s it, the CSS style attribute has been applied dynamically using ngStyle attribute directive.

Also See:

References:

Leave a Reply

avatar
  Subscribe  
Notify of