Categories

Sep 18, 2019 in Angular

Q: Angular ngclass

1 Answer

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.

Ready?

Let's get started!

angular-ngclass-old-way

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?

angular-ngclass-banner

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>
Click here to read more about Angular JS
Click here to read more about Insurance

Related questions

Madanswer
Feb 15 in Angular
Feb 15 in Angular
Feb 15 in Angular
...