Quick Tip

Quick Tip: Snippets to Add Styles to Angular v2+ Templates

Angular allows for many different ways to add classes to your templates. We'll explore the different ways including:

  • class property bindings: [class] and [className]
  • style property bindings: [style]
  • The ngClass directive
  • The ngStyle directive

Using Property Bindings

With property bindings, Angular allows us to grab the HTML attributes directly. This way, don't have to remember any extra directives. We can just use the HTML attributes we already know.

In this example, we'll be using [class] and [style] with the Angular property bindings [].

Using the class Property Binding

We can call class and the class name that we want to use. Whatever is on the right side of the = will be evaluated to be truthy or falsy. If truthy, Angular will apply the class.

// using class
<div [class.isActive]="myIsActiveVariable"></div>

// using className
<div [className]="'goBlue'"></div>

<div [className]="myClassVariable"></div>

Using the style Property Binding

In addition to binding to class and className, we can bind to style.

// a simple implementation
[style.color]="'blue'"
// in the class
myColor = 'red';
[style.color]="myColor"

// both of the following work
[style.background-color]="myColor"
[style.backgroundColor]="myColor"

Using ngClass

The ngClass Angular directive provides us many different ways we can bind classes to our elements.

The benefit of using ngClass is that it will be easy to bind multiple classes:

<!-- bind 2 classes directly with an array -->
<div [ngClass]="['firstClass', 'secondClass']"></div>

<!-- same result, bind 2 classes as a full string -->
<div [ngClass]="'firstClass secondClass'"></div>

<!-- evaulate each class to see if it should be applied -->
<div [ngClass]="{ firstClass: isFirstActive, secondClass: isSecondActive }"></div>

Using ngStyle

The ngStyle Angular directive allows us to bind styles directly to an element's style attribute. Instead of adding a class, we can directly apply the style.

<!-- a simple ngstyle usage -->
<div [ngStyle]="{ color: red }"></div>

<div [ngStyle]="{ color: isDanger }"></div>

<!-- when binding to an attribute with a dash, make sure you use single quotes -->
<div [ngStyle]="{ 'background-color': 'blue', 'font-size': '17px' }"></div>

<!-- bind the width as a specific measurement -->
<div [ngStyle]="{ 'width.%': myVariable }"></div>
<div [ngStyle]="{ 'width.px': myVariable }"></div>

Conclusion

Using the above tactics, it's easy to add styling to your Angular v2+ templates!

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.