Hi everyone. In this tutorial I’m gonna talk about Class and Style Bindings in Angular 2.
Let’s remember, in previous tutorial, we wrote a component like this:
Now, we will change template and styles properties and define a new property in Angular2Tutorials class.
Firstly, let’s take a look at the class binding.
- We defined a div tag in template property. In this div tag, we calling our css class in square brackets like [class.myClass] and assigning a value, applyClass, to this css property.
- In styles property we defined a css class that is myClass. This class only changes color of text to red.
- In Angular2Tutorials class, we defined a property that is applyClass and used it in template property. [class.myClass]=”applyClass” definition checks value of applyClass. If applyClass is equal to true, myClass css property is assigned to class property of div. If it is false, nothing happens.
When I check the main page, I see this. The applyClass property is equal to true and color of text is red.
Now, let’s take a look at style binding. We will define another div tag in template attribute and another property in class. Our component will be like this:
- We defined another div tag which has a color style. The color of text is changing according to value of applyBlue. We used again square brackets and called our applyBlue property.
- We used an if-else expression like in programming languages in template attribute. If the value of applyBlue property is equal to true, the color of text will be blue. If not, the color of text will be orange.
- In class body initially, we defined value of applyBlue as true.
When I look at the main page, I see this screen. The color of text that’s in second div is blue.
Now, I change value of applyBlue property to false and check again the main page.The color ot text is orange.
When we finished this tutorial
- We learned CSS class binding in Agular 2
- We learned CSS style binding in Agular 2
Until the next article, take you care.
With Greetings And Love