Sep 18, 2019 in Angular
Q: Angular ngclass

1 Answer

0 votes
Sep 19, 2019
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.

Before we do that, we take a look at how CSS classes are assigned using regular JavaScript and then compare that to the angular way.


Let's get started!


Adding CSS classes without Angular

So how did we assign CSS classes in JavaScript before we knew 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')

Afterward, we could use the JavaScript DOM-API to assign a className.

element.className = 'example-class'

DOM-Manipulation in plain old JavaScript always felt like a pain.

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

Angular, like other single page application frameworks, realy shines when it comes to data-binding. That means, that the DOM is automatically updated, whenever the corresponding JavaScript object changes.

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.

<div [className]="'example-class'"></div>

Related questions

+1 vote
Jul 5 in Angular
+1 vote
Jul 5 in Angular