Angular 7 ngStyle Directive

Style elements dynamically with ngStyle:

To change or style the properties like value, color, and the size of the elements in Angular, the ngStyle attribute is used.

Example 1:

component.ts file:

import {Component} from '@angular/core';  
@Component(  
  {selector: 'app-server',  
    templateUrl: 'server.component.html'})  
export class ServerComponent {  
serverID = 20;
 serverStatus = 'Online';
 
 constructor() {
   this.serverStatus = Math.random() > 0.5 ? 'Offline' : 'Online';
 }
 getServerStatus() {
   return this.serverStatus;
 }
}

component.html file:

<p>Server with ID {{serverID}} is {{serverStatus}}. </p>

Output 1:

Output 2:

Explanation:

In the above example, we are choosing a method to show the server randomly to be “Online” and “Offline”. Thus, there is a 50% chance for both.

Example 2: Use of ngStyle attribute with property binding to configure it:

component.html file:

<p [ngStyle]="{backgroundColor: getColor()}"> Server with ID {{serverID}} is {{serverStatus}}. </p>

Output 1:

Output 2:

Explanation:

In the above example, we are creating a method getColor() to change the color dynamically. Here, we are changing the background color ‘red’ when the server is offline and “green” when the server is online.

To apply CSS classes dynamically with ngClass:

We can also use ngClass directive to add or remove a CSS dynamically, or in simple words, to apply a CSS class to an element.

Example:

component.ts file:

import {Component} from '@angular/core';  
@Component(  
  {selector: 'app-server',  
    templateUrl: 'server.component.html',  
    styles: [`  
    .Online{  
      color: white;  
    }`]  
 
  })  
export class ServerComponent {  
  serverID = 20;
 serverStatus = 'Offline';
 
 constructor() {
   this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline';
 }
 getServerStatus() {
   return this.serverStatus;
 }
 getColor() {
   return this.serverStatus === 'Online' ? 'brown' : 'crimson';
 }
}

component.html file:

<p [ngStyle]="{backgroundColor: getColor()}"  
[ngClass]="{Online: serverStatus === 'Online'}"> Server with ID {{serverID}} is {{serverStatus}}. </p>

Output 1:

Output 2:

Explanation:

In the above example, we are creating a class in component.ts file. This class changes the color of the text to white in case the server is online. Here, the ngClass directive is used with property binding when applying CSS class dynamically.

Please Share