AngularT2 Dark_1200x303

Data binding can be confusing when you’re getting started in Angular. Let’s break it down! This post covers one-way style binding.

In today’s post, we will look into style binding in Angular and how you can bind CSS styles to your templates easily. This is one of the articles in the data binding series we have been looking into lately.

Prerequisites

This post is suited for all levels of frontend developers who use Angular, so being conversant with beginner concepts and installation processes is not assumed. Here are a few prerequisites you should have before you start to use Angular 12 and follow along through this article’s demonstration:

  • VS Code as your integrated development environment
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation)
  • Angular CLI version 8.0 or above
  • The latest version of Angular (version 12)
// run the command in a terminal
ng version

Confirm that you are using version 12, and update to 12 if you are not.

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

What Is Style Binding?

Similar to property binding, style binding is used to specify inline styling for template elements in your component. You can style any template element on the go using this approach in the most scalable way. This is because you can define the style value inside the component. This also allows you to do inline styling dynamically. You can also put conditions on the style rules you write. Style binding was created to give you more power when designing a component in the template file.

The syntax of style binding looks like this:

<element [style.style-property] = "'value'">

What We Are Building

We are going to use the Angular CLI to generate a new test application where we can test out style binding and show how you can easily use it in your workflow today.

Open your VS Code in the location of your choice, open the terminal and run this command:

ng new styleapp

Make sure to answer the prompts like this:

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS

Now your new project has been generated. Navigate into it like this:

cd styleapp
ng serve

Now navigate to the src folder and inside the app component.html file, copy the styles there into the app.component.css file, and then replace the content of the application with the code block below:

<div class="toolbar" role="banner">
  <span>Welcome</span>
    <div class="spacer"></div>
    <a aria-label="Angular on twitter" target="_blank" rel="noopener" href="https://twitter.com/angular" title="Twitter">
    </a>
</div>
<div class="content" role="main">
<!-- Highlight Card -->
  <div class="card highlight-card card-small">
<svg id="rocket" alt="Rocket Ship" xmlns="http://www.w3.org/2000/svg" width="101.678" height="101.678" viewBox="0 0 101.678 101.678">
      <g id="Group_83" data-name="Group 83" transform="translate(-141 -696)">
        <circle id="Ellipse_8" data-name="Ellipse 8" cx="50.839" cy="50.839" r="50.839" transform="translate(141 696)" fill="#dd0031"/>
      </g>
    </svg>
<span>{{ title }} app is running!</span>
<svg id="rocket-smoke" alt="Rocket Ship Smoke" xmlns="http://www.w3.org/2000/svg" width="516.119" height="1083.632" viewBox="0 0 516.119 1083.632">
    </svg>
</div>
<!-- Resources -->
  <h2>Resources</h2>
  <p>Here are some links to help you get started:</p>
<div class="card-container">
    <a class="card" target="_blank" rel="noopener" href=#>
      <svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>
<span>Hello</span>
<svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>    </a>
<a class="card" target="_blank" rel="noopener" href=#>
      <svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>
<span>Hello</span>
<svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>
    </a>
<a class="card" target="_blank" rel="noopener" href=#>
      <svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>
<span>Hello</span>
<svg class="material-icons" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"></svg>
    </a>
</div>
</div>

If you run the command below in your terminal, the app should now look like this:

ng serve

Angular app showing styleapp is now running! Resources - Here are some links to help you get started: with three side-by-side cards/buttons, all labeled Hello. The third one has a shadow around it, looking elevated.

Inline Styling in Angular

Normally in Angular templates, just like in any HTML file, you can use inline styling for your elements. Let’s use the h2 element that displays Resources, for example, to change the style and make it bigger. All you have to do is to add this inline style inside the h2 tag like this:

<h2 style="font-size: 100px">Resources</h2>

Now if you refresh the app, you’ll see that the font is bigger now. You can even add additional rules to one single element like this:

<h2 style="font-size: 100px; color: cornflowerblue;">Resources</h2>

Now the font and the colors of this element are styled according to these two rules.

The Resources label is now much larger and in light blue instead of black.

Using Style Binding in Angular

Now remember our syntax above for style binding:

<element [style.style-property] = "'value'">

Let us apply that to the same header element we used above.

<h2 [style.font-size] = "'100px'"> Resources</h2>

This returns exactly the same thing as the normal inline styling.

Resources is duplicated, large and in black

This is exactly how style binding is done. You can see how similar it is to property binding. It serves the same purpose as the normal inline styling but comes with even more power, features and flexibility.

Casing in Style Binding

With style binding, you can use both the hyphen-casing (font-size) and the camel-casing (fontSize) approaches. Angular made it really easy for anyone, no matter their styling backgrounds, to pick up style binding. Let us try it out:

<h2 [style.font-size]="'100px'">Resources</h2>
<h2 [style.fontSize]="'100px'">Resources</h2>

You see they give the same exact result so it does not matter which approach you want to take.

Dynamic Style Binding

At this point, you might be asking what the difference is between inline styling and style binding. The main difference is you can bind data values using style binding. Using our simple example, navigate to the app.component.ts file and replace the content with the code block below:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'styleapp';
  rules = 'font-size: 100px; color: cornflowerblue;';
  rule = '100px';
}

Now inside the HTML file, change the value properties in the headers to rules like this:

<h2 style="rule">Resources</h2>
<h2 [style.font-size]="rule">Resources</h2>
<h2 [style.fontSize]="rule">Resources</h2>

You will see that an error occurs on the normal inline styling—it is not possible to bind to the normal inline style. However, with style binding, it works well. The ability for you to dynamically change the value of style rules in the template is one of the main reasons style binding exists.

Adding Conditions

By now you are beginning to notice that the possibilities are endless with what you can do using style binding. Let us add conditions to values we change dynamically. In your app.component.ts file, add a new variable called check:

check = true

In the template file, change one of the header tags to this:

<h2 [style.fontSize]="check? '100px' : '200px'">Resources</h2>

Basically, this saying that if the check value is true, let the font be 100 pixels, and if it is false, let it be 200. This is a simple use case showing how we can utilize the power of style binding in our workflow today.

Conclusion

In today’s post, we took a look at style binding in Angular, we learned about how it is similar to inline styling and the differences too. We saw how we can do more with our inline styles using the power of style binding. Stay tuned for more data binding content. Happy hacking!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.