NgClass: How to assign CSS classes in Angular
In this tutorial, we are going to take a look how we can use CSS classes with angular.
We will take a look at different methods to dynamically assign a CSS class to an element using the className directive.
We will also learn, how we can toggle that class on or off, depending on the state of the application with NgClass.
Let's get started!
Adding CSS classes without Angular
First of all, we had to find the DOM-element we wanted to assign the class to. In the best case, we would find that element by id like this:
let element = document.getElementById('exampleDiv')
element.className = 'example-class'
This is no exception.
Maybe this example is to simple to point that out properly, but what would you do if you wanted to assign a class based on a codition?
How to assign a CSS class in Angular using the [className] property binding
This is the same for CSS classes.
We can just bind a property to the className attribute of our HTML-elements. Just like we would with other attributes like img-src.