Telerik blogs
AngularT2 Dark_1200x303

In this post we look at style binding and also at the ngStyle directive and how it helps solve for the limitations that style bindings have had in the past. These are some handy tricks when you’re getting started in Angular!

Angular

Angular, Google’s JavaScript (TypeScript) framework for building web applications, mobile or desktop, has over 72,000 stars on GitHub. It’s maintained by the Angular team at Google and a host of community members and organisations.

Before You Start

To be able to follow through in this article’s demonstration you should have:

  • An integrated development environment like VS Code
  • Node version 11.0 or higher installed on your machine
  • Node Package Manager version 6.7 or higher (usually ships with Node installation)
  • Angular CLI version 8.0 or higher
  • Version 8 of Angular or higher
  • Download this tutorial’s starter project here to follow through the demonstrations.
  • Unzip the project and initialize the node modules in your terminal with this command:
npm install

In this post, you will learn how to use the ngStyle directive for component element styling in your Angular projects.

Styles in Angular

Angular is designed to be very modular and component based, this means that every component has its own style sheet and the styles defined inside are scoped to that particular component by default. There is also a global style sheet for global styles in the root directory of every Angular project.

Style Binding

In Angular, you can easily apply inline styles to HTML elements of your choice with style binding. Let’s dive into how this is actually done

Demo

If you followed this post from the start, you would have downloaded and unzipped the Angular canvas from GitHub. Let us see how these work in a real Angular application that prints and styles tech courses in a university portal. Load up the app in your integrated development environment (I use VS Code) and open the app.component.html file and clean it up to look like this:

<div style="text-align:center">
  <h1> Welcome to the Fake Tech University </h1>
</div>
<app-courses></app-courses>
<router-outlet></router-outlet>

To keep things modular, let’s create a new component, and call it courses. In your terminal, run this command below:

ng generate component courses

Open your courses.component.ts file and replace the code there with the code block below:

import { Component, OnInit } from "@angular/core";
@Component({
  selector: "app-courses",
  templateUrl: "./courses.component.html",
  styleUrls: ["./courses.component.css"]
})
export class CoursesComponent implements OnInit {
public isCourse = true;
courses = [
    {
      name: "Introduction to Web Development",
      level: "Beginner",
      color: "green"
    },
    {
      name: "Understanding APIs",
      level: "Beginner",
      color: "green"
    },
    {
      name: "Introduction to Docker Containers",
      level: "Advanced",
      color: "red"
    },
    {
      name: "Understanding Time complexities",
      level: "Advanced",
      color: "red"
    },
    {
      name: "Algorithms and Data Structures",
      level: "Advanced",
      color: "red"
    },
    {
      name: "My first HTML page",
      level: "Beginner",
      color: "green"
    },
    {
      name: "Ways to use CSS in your web page",
      level: "Beginner",
      color: "green"
    },
    {
      name: "Introduction to Unit testing",
      level: "Beginner",
      color: "green"
    },
    {
      name: "What are PWAs",
      level: "Beginner",
      color: "green"
    }
  ];
  constructor() {}
  ngOnInit() {}
}

In this component, I created an array of objects of all the tech courses and their various levels for the semester.

Now for the presentation, go to the courses.component.html file and replace the placeholder content with the code block below inside it:

<p>
  All Beginner courses are colored green and all advanced courses are colored red.
</p>
<ul>
  <li *ngFor="let course of courses">
    {{ course.name }}
    </li>
</ul>

If you run the application now you will see that it looks something like this:

A simple white background with black text. Despite a sentence that says, "All Beginner courses are colored green, all intermediate courses are colored blue and all advanced courses are colored red," all the text is black.

To style the component using the style binding approach, let us make all the list items green. Inside your courses.component.html file, copy the code block below:

<p>
  All Beginner courses are colored green, all intermediate courses are colored
  blue and all advanced courses are colored red.
</p>
<ul>
  <li *ngFor="let course of courses" [style.color]="'green'">
    {{ course.name }}
  </li>
</ul>

If you save the file and go back to the browser, you will find that all the list items are now colored green.

You can decide to define the colors in your array or object and then assign the property to the style rule instead of explicitly setting “green” like so:

<p>
  All Beginner courses are colored green, all intermediate courses are colored
  blue and all advanced courses are colored red.
</p>
<ul>
  <li *ngFor="let course of courses" [style.color]="course.color">
    {{ course.name }}
  </li>
</ul>

The application in your browser at localhost:4200 should look like this:

In the same course list, now some of the courses are shown in green and some in red.

What if we wanted to add conditions to these inline styling?

Using Conditions

Remember we had a class definition isCourse in our courses.component.ts file? Using that, we can specify a condition for a style to be applied like this:

<p>
  All Beginner courses are colored green, all intermediate courses are colored
  blue and all advanced courses are colored red.
</p>
<ul>
  <li *ngFor="let course of courses" [style.color]="isCourse? 'red': 'green'">
    {{ course.name }}
  </li>
</ul>

This tells Angular to make the color of the list items red if the isCourse class is true and if not, make it green.

Limitation of the Style Binding Approach

Style binding as we have seen so far has a limitation. Imagine you also wanted to change the font size of the application we are using today. Your code block would look like this:


<ul>
<li *ngFor="let course of courses" [style.color]="isCourse? 'red': 'green'"
[style.font-size]="'24px'">
  {{ course.name }}
</li>
</ul>

You can already see how inefficient and messy your presentation will look with a lot of styles defined independent of the other. The Angular team solved this problem with the ngStyle directive.

ngStyle Directive

ngStyle is an attribute directive that updates styles for the containing HTML element in your component. It is used to set one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional . suffix (such as “top.px”, “font-style.em”). The value is an expression to be evaluated. The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of evaluation is null, the corresponding style is removed.

Here is how it is implemented by Angular:

@Input()
ngStyle: { [klass: string]: any; }

How It Is Used

It is used like an object declaration, so you can have more than one CSS style rule, separated by commas. For our demo application, joining the two styles about font and color with ngStyle can be simply done like this:

<p>
  All Beginner courses are colored green and all advanced courses are colored
  red.
</p>
<ul>
  <li *ngFor="let course of courses" 
  [ngStyle]="{'color': course.color, 'font-size':'24px'}"> 
    {{ course.name }}
  </li>
</ul>

It would look like this in your browser when you save your files in the VS Code IDE:

In the same course list, with some of the courses shown in green and some in red, the courses are all in a larger font.

With this you can lay out more than one style rule for an element or a set of elements from loops or conditionals. The complete code to this tutorial can be found here on GitHub.

Conclusion

This is an overview of style binding and how it is done in Angular. We also looked at the ngStyle directive and how it helps solve for the limitations that style bindings were having in the past. 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.