Angular Built-in Attribute Directives - NgClass

This is the first of three lessons about built-in Angular directives. There are three lessons in this course about attribute built-in directives, which will be followed by three lessons about structural directives. Let’s begin with the NgClass directives.

What is an NgClass

An NgClass is a directive provided to us by Angular, and it’s ready to use in every project in this framework. It’s an attribute directive, which means it modifies the behavior or appearance of the existing elements. As its name suggests, this directive particularly focuses on appearance (the “Class” in NgClass relates to CSS class).

When is it useful?

Before we introduce the actual directive and its syntax, let’s talk about its use casee. In most cases, we can implement styles in a static way, like this:

<button class="app-button">Hello</button>

As we can see, there’s a button with one CSS class applied to it. Let’s imagine that the class represents a base style for the buttons in our application. If we have one more class in our stylesheets, that class could be applied to a button.

.button-active {
	background-color: blue;

This class, however, needs to be added to the button in a very specific case. Let’s say we want the button to have a blue background but only if the form in the component is valid. In other words, we want to dynamically add or remove CSS classes from elements in the component template. That’s exactly what the NgClass directive is designed to do!

Using NgClass applies CSS classes dynamically by implementing the provided expression. The expression can be any of the following:

  • A string
  • An array of strings
  • An object

Get hands-on with 1200+ tech skills courses.