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.
I recommend going through my previous articles from the beginning for better understanding.
- Architecture Angular 2 Part: 1
- Getting Started with Angular 2 Part: 2
- Understanding Application Files in Angular 2 Part: 3
- Simple Hello world Application in Angular 2 Part: 4
- Creating our first component in Angular 2 Part: 5
- Style Components in Angular 2 Part: 6
- Data Binding In Angular 2 Part 7
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
- @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:
Casino Games | Dr. Maryland
ReplyDeleteCasino Games - Enjoy 경산 출장안마 all of your favorite casino games 남원 출장마사지 and slots at a great deal of the 안성 출장샵 time. Dr. Maryland has partnered with 김해 출장마사지 top tier brands, 동해 출장샵 Rating: 4.5 · 32 reviews