NgClass vs Class Binding in Angular

Amitav Mishra
Oct 5 · 2 min read
Image for post
Image for post
Photo by Markus Winkler on Unsplash

Like data, we can bind classes to elements in angular. To set some style conditionally on any element we can simply write the CSS styles on a class selector and we can add that CSS class conditionally to any element.

Class Binding

To add or remove a CSS class dynamically from an element we can make use of class binding. Syntax is:

[classs.className] = "boolean expression"

If the given Boolean expression is truthy then the provided class will be added or if it is falsy then it will be removed from the element. For Example:

<div [class.error]="hasError"> </div><div [class.adult]="age >= 18 ? true : false"> </div>

With class binding, we can add only single class conditionally. However to set multiple classes we can use directive.

The ngClass Directive

To add multiple classes, we can pass an object where key will be class names and values will be respective boolean expressions.

<div [ngClass]="{'error': hasError, 'warning': hasWarning}"> </div>

If the boolean expression is truthy, the respective class will be added to the element.

If we have more complex object to pass to , we can also define the object in the component and we can use that object in the template.

TS

classes = {
'hasValue': this.password.length > 0,
'valid': this.password.length >= 6,
'invalid': this.password.length < 6,
}

HTML

<div [ngClass]="classes"> </div>

We can also pass string and array values to .

<div [ngClass]="'box'"> </div><div [ngClass]="['box', 'card', 'container']"> </div>

Now you are all set to add dynamic classes to your HTML elements with whichever binding appropriate for you.

Thanks for your time☺️
For more Web development blogs, Please visit jscurious.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store