FlipKart

Recent Posts

Class and Style Bindings in Angular 2




In this article, we are going to learn how to bind classes and styles to an HTML element using TypeScript code in the Angular framework.



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

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 an HTML element.
First, let us create a new class, as shown below


 Code:
  • @Component({
  • selector: "my-tuts",
  • template: `<h2>{{title}}</h2>`,
  • styles: [`.myClass{
  • color:red;
  • }']
  • })
What does class binding do? It is going to assign a class to HTML elements, which is based on an expression, which evaluates as true or false. Let’s create a div tag, as shown below.
  • <div [class.myClass]=" ">Apply Class Binding</div>`,
Here, my class to apply is myClass, as shown above.
The 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.
  • <div [class.myClass]="applyclass">Apply Class Binding</div>`,
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.
Code:
  • export class RathrolaComponent {  
  • public title = "Tutorials from Rathrola";  
  • public applyclass = true;  
  • public applyblue = true;  
  • }
Now, let’s create another div tag, as shown below.
  • <div [style.color]="applyblue?'blue':orange">Blue</div>`,
In order to specify inline style by using style binding, we are going to make use of square brackets again, as shown above. 
We can also write something like ab if condition in a div tag, as shown below.
  • <div [style.color]="applyblue?'blue':orange">Blue</div>`,
The output is shown below: 
If the two variables are false, we'll use the code given below.
export class RathrolaComponent {  
    public title = "Tutorials from Rathrola";  
    public applyclass = false;  
    public applyblue = false;  
}
The output is shown below.
In our next article, we'll take a look at Event Binding and References.
Thanks for reading my article!

No comments