Introduction

Sometimes when working on an application, you might want to dynamically style an element depending on a certain condition. This can be done using either ngStyle or ngClass depending on your situation.

What is the difference between ngStyle and ngClass?

ngStyle takes a JavaScript object and transforms it into an attribute. ngClass on the other hand transforms a JavaScript object into a CSS class.

Using ngStyle

Suppose your component displays a list of users in a system. In the component class you have a string variable called userStatus. You can use that variable as a conditional in your template to determine whether you should change the background colour depending on the status of the user. If the status of the user is “deleted”, we will make the background colour of the button red. Otherwise, it will be green. Here’s how to implement that in the template of your component using ngStyle:

<p id="user-status" [ngStyle]="userStatus === 'deleted' ? 'background-color: red' : 'background-color: green'">{{userStatus}}</p>

Using ngClass

Let’s say we prefer to use badges to show whether a user is active or inactive. We can use ngClass here to accomplish this task. Let’s assume this time that userStatus is a boolean instead of a string. This is how it can be implemented in the template of your component using badges from Bootstrap:

<p [ngClass]="userStatus === 'Active' ? 'badge badge-success' : 'badge badge-danger'">{{userStatus}}</p>