Class And Style Bindings In Angular 2 - Part Eight

From our previous article, we learned about Data Binding in Angular 2 Application,

I recommend going through my previous articles from the beginning for better understanding.
In this article, we are going to learn how to bind classes and styles to HTML element.

First, let us create a new class, as shown below


  1. @Component({  
  2.             selector: "my-tuts",  
  3.             template: `<h2>{{title}}</h2>`,  
  4.             styles: [`.myClass{  
  5. color:red;  
  6. }']  
  7. })   

What does class binding do? It is going to assign a class to HTML elements, which is based on an expression, which evaluates true or false. Let’s create a div tag, as shown below.

  1. <div [class.myClass]=" ">Apply Class Binding</div>`,  

Now, to apply class binding, we make use of class property and we use a dot, followed by the class, which we want to apply or not apply based on the condition.

Here, my class to apply is myClass, as shown above.

Class is going to be assigned to div tag, which is based on a variable of true or false.

Let us create a variable, as shown below.


Now, apply this variable in div component, as shown below. 

  1. <div [class.myClass]="applyclass">Apply Class Binding</div>`,   

If the variable is true, then assigned div tag will have Red color.

When we save and run the Application, the output will be, as shown below.


That’s how class binding works. Similarly, we have style binding in order to apply inline styles to HTML elements.

Let’s create another property, as shown below. 


  1. export class RathrolaComponent {  
  2.     public title = "Tutorials from Rathrola";  
  3.     public applyclass = true;  
  4.     public applyblue = true;  
  5. }   

Now, let’s create another div tag, as shown below.


  1. <div [style.color]="applyblue?'blue':orange">Blue</div>`,   

In order to specify inline styles by style binding, we are going to be making use of square brackets again, as shown above.

We can also write something like if condition in div tag, as shown below.

  1. <div [style.color]="applyblue?'blue':orange">Blue</div>`,  

The output is shown below.


If the two variables are false, as given below.

  1. export class RathrolaComponent {  
  2.     public title = "Tutorials from Rathrola";  
  3.     public applyclass = false;  
  4.     public applyblue = false;  
  5. }  

The output is shown below.


In our next article, we shall see Event Binding & References.

Thanks for reading my article.