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
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:
- Two-Way Data Binding – Example
- HTML Property Binding in Angular : Data Binding
- Create a new component in Angular 9 with CLI and without CLI
- How to include Bootstrap to your Angular 9 Project ?
- Store access token in Ionic Angular App local storage securely
- Angular TypeScript Vs ES6 Vs ES5
- Port 4200 is already in use while running ng serve Angular CLI command
- String Interpolation in Angular 9
- This version of CLI is only compatible with Angular versions
- Your global Angular CLI version is greater than your local version
- Difference between Constructor and ngOnInit in Angular 9
- Create custom events and fire in Angular 9 with EventEmitter – Example
- How to use *ngIf else in Angular 9 template with Example ?
- Angular 9 : Dynamic and conditional CSS classes with ngClass