Angular Built-in Directives: ngClass

Previously, we learned about ngStyle. This time, we will talk about ngClass. ngClass is similar to ngStyle but with ngClass, you can add or remove a whole set of CSS classes on an HTML element.


You can use Angular ngClass in three ways:


  • Strings are listed as a single list that are separated only by space.
  • Arrays are the elements inside a “[ ]” and separated by commas.
  • Objects uses CSS class names with specific values.

Now let’s try looking at it in code. Go back to stocks.component.ts and add the style class on your @Component decorator.

Then let’s use this class to make the ngSwitch case we made earlier to color violet.

In this case, our ‘market’ variable equals to ‘NASDAQ’ that is colored violet by our custom class. So the output should be:


Let’s add more styles to our custom class. And we will use the three types of format when using Angular ngClass. First we need to add another style for our style class.


Now we have a style that determines the color and another style that determines the alignment of the list. Then, as we’ve said earlier, ngClass has three ways of format:

(1) String type ngClass

(2) Array type ngClass

(3) Object type ngClass

Just like the previous directives, you can also create variables to create the constant variables that were hardcoded in our style class.

Save your work and go back to your browser. The output should like this:


On the next section, we will tackle Services.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.