Angular Classes with NgClass

With Angular, we have many approaches to adding, removing, toggling classes. We can choose single classes and bind a property, or we can use the awesome NgClass directive from Angular.
In this post, we’ll explore class bindings, and also Angular’s NgClass directive, the syntaxes and also some best practice ideas.

Table of contents

Property Binding with className
Property binding with “class”
Angular’s NgClass Directive
Multiple Classes with NgClass
Mixing class and NgClass

It’s a frequent requirement to add some kind of “state” to the DOM, typically via classes. Let’s explore some quick and easy options we have with Angular.
Property Binding with className
Before we jump into NgClass, let’s explore some sugar syntax that’s simple yet effective. When working with single classes, I much prefer and advocate this approach over diving into NgClass, it’s faster to work with and I find it’s more descriptive when analysing existing code.
So, what does it look like?
In JavaScript DOM, we have a className property available on DOM elements:
const div = document.querySelector(‘div’);
div.className = ‘hello’;
console.log(div.className); // ‘hello’

Nice and easy. But, in Angular we’re working with templates and bindings – not DOM APIs such as querySelector.
In Angular, we bind to properties, not attribute. Which means we can turn this knowledge into: