CSS Style Binding in Angular

In Angular, you can also directly Add styles to a block. This is done using a tag attribute written in the following format:

html[style.styleProperty]="property value"

In this case, the names of CSS properties that have a hyphen inside them will be written in camelCase. Let's look at examples of how this works.

Example

Let's set a background for the element:

app/app.component.html<div [style.backgroundColor]="'blue'">
  text
</div>

Example

Let's say we have some property that contains the background color:

app/app.component.tsexport class AppComponent {
  public value: string = 'red';
}

Let's apply this property as a value for the style:

app/app.component.html<div [style.backgroundColor]="value">
  text
</div>

Example

Let us have some Boolean property:

app/app.component.tsexport class AppComponent {
  public isActive: boolean = true;
}

We will bind different values ​​to a CSS property depending on the contents of a boolean property. We will use the ternary operator for this:

app/app.component.html<div [style.backgroundColor]="isActive ? 'blue' : 'red'">
  text
</div>

Practical tasks

Задание 1

Given a block, make it so that the first click on the block paints it red, and the second click paints it green.

Задание 2

Given a block. Given a button. Make it so that pressing the button doubles the width of the block.