Angular Class Binding

In the previous article, you’ve learned about Angular property binding and its use. This article will be about class binding in angular. Like property binding, we can also bind classes in angular.

What is Class-Binding in Angular?

Basically, Class Binding in angular is used to create a styled element dynamically. We can add or remove classes to and from the HTML elements by applying some conditions.

Example 1

Before moving into class-binding, let’s make two classes in app.component.css and first see how we add regular classes into HTML elements.

.success{
  color: green;
}
.danger{
  color: red;
}
  • success class changes the HTML element color to green when the
  • danger class changes the HTML element color to red when

NOTE: “.” represents class, and “#” represents id in CSS.

Now let see the Syntax of adding regular class:

<h1 class=”success”>CLASS BINDING TUTORIAL</h1>

Output:

angular class binding example 1

Now, like property binding, we can bind classes in the same way. The syntax is quite the same here.

Syntax

<h1 [class]="dangerClass">CLASS BINDING TUTORIAL</h1>

dangerClass is defined in the component.ts file, which contains the danger class.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  successClass = "success";
  dangerClass = "danger";
}

Output:

angular class binding example 2

NOTE: The use of class binding and class attributes simultaneously is a terrible idea as class binding will get preference every time.

Example 2

Well, there is another syntax of class binding called ngClass directive. This syntax applies to multiple classes based on an expression that evaluates to be either true or false.

Let’s see the syntax:

<h1 [ngClass]="displayClass">CLASS BINDING TUTORIAL</h1>

displayClass is a property defined in the component.ts file.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  hasError = true;
  displayClass = {
    "success":!this.hasError,
    "danger": this.hasError
  }
}

Here the color of the text can be toggled and will depend upon the hasError property.

For example, in the above typescript file, the hasError is set to true. Hence the text color will appear red.

angular class binding example 3

Conclusion

We hope this tutorial has made your concept crystal clear on Class Binding on Angular. Class Binding is another important topic we’ll use when changing the element’s style based on certain conditions. In the upcoming articles, We’ll also learn Style Binding and Event Binding as well.

Read Next: Angular Style Binding

Leave a Reply

Your email address will not be published. Required fields are marked *