Categories

1 Answer

Sep 13, 2019

Style elements dynamically with ngStyle

The ngStyle attribute is used to change or style the multiple properties of Angular. You can change the value, color, and size etc. of the elements.

Let's see this by an example:

component.ts file:

  1. import {Component} from '@angular/core';  
  2. @Component(  
  3.   {selector: 'app-server',  
  4.     templateUrl: 'server.component.html'})  
  5. export class ServerComponent {  
  6.   serverID: number = 10;  
  7.   serverStatus: string = 'Offline';  
  8.   
  9.   constructor () {  
  10.   this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline';  
  11. }  
  12.  getServerStatus() {  
  13.   return this.serverStatus;  
  14.   }  
  15. }  

component.html file:

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

Output:

Style elements dynamically with ngStyle

Let's use ngStyle to change the background color 'red' when the server is offline and "green" when the server is online.

component.html file:

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

Output:

Style elements dynamically with ngStyle

If both servers are online, it will be as:

Style elements dynamically with ngStyle

This is the example of ngStyle attribute with property binding to configure it.

How to apply CSS classes dynamically with ngClass

In the previous article, we have seen that how to use ngStyle to make changes in an element dynamically. Here, we shall use ngClass directive to apply a CSS class to the element. It facilitates you to add or remove a CSS dynamically.

Example:

Let's create a class in component.ts file which will change the color of the text yellow if the server is online.

component.ts file:

  1. import {Component} from '@angular/core';  
  2. @Component(  
  3.   {selector: 'app-server',  
  4.     templateUrl: 'server.component.html',  
  5.     styles: [`  
  6.     .Online{  
  7.       color: yellow;  
  8.     }`]  
  9.   
  10.   })  
  11. export class ServerComponent {  
  12.   serverID: number = 10;  
  13.   serverStatus: string = 'Offline';  
  14.   
  15.   constructor () {  
  16.     this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline';  
  17.   }  
  18.   getServerStatus() {  
  19.     return this.serverStatus;  
  20.   }  
  21.   getColor() {  
  22.     return this.serverStatus === 'Online' ? 'green' : 'red';  
  23.   }  
  24. }  
Click here to read more about Angular JS
Click here to read more about Insurance

Related questions

Madanswer
Sep 13, 2019 in Angular
Sep 13, 2019 in Angular
Sep 13, 2019 in Angular
...