Style elements dynamically with ngStyleThe 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: component.html file: Here, we have chosen a method to show the method randomly "Online" and "Offline". There is 50% chance. Output: 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: Here, we have created a method getColor() to change the color dynamically. Output: If both servers are online, it will be as: This is the example of ngStyle attribute with property binding to configure it. How to apply CSS classes dynamically with ngClassIn 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: component.html file: Output: You can see that the ngClass directive has changed the color of the text which is online. This is an example of ngClass directive with property binding applying CSS class dynamically. Next TopicAngular 7 Databinding |