Binding with Style in Aurelia

One of my favourite features of Aurelia is the ability to bind element styles. If you ever worked with Angular 1, then you would know you could bind not only classes but inline styles on an element as well.

Please note:
In all of these examples except String Interpolation, you can use the style attribute, but it is recommended that you use css for Internet Explorer compatibility if you want to use interpolation. I personally just use css for all style binding use-cases, which is an alias for style anyway.

Style binding using objects

Using an object in your ViewModel or defined in your view template, you can bind multiple styles to one or more elements.

Please note: changes to property values in an object will not update in your view as object properties are not observed. The entire object needs to be replaced if you want the view to see changed values.

Inline style object

You can define an object right within your view template, no need to define a ViewModel object if you’re only intending on supplying values inline for whatever reason.

My Text

ViewModel object

In most cases when you use objects for defining inline styling, you will define them inside of your ViewModel and then reference that class variable inside of your view template.

Please note:
When a property value changes, your styles will not dynamically update. For example changing the property value of color below will not update the view with your new colour value. This is because object values are not individually observed. However, if you replace the object entirely, your changes will update as intended.

export class MyClass {
    myCss = {
        color: 'red'
    };
}

Style binding using strings

Very similar to the above example of using an object, except all styles are defined inside of a string and resemble what your style would look like if defined inline using a standard non binding style attribute. Replacing the string with a new value will result in your view seeing the updated changes.

export class MyClass {
    myCss = 'width: 400px; height: 250px; color: red';
}

Style binding using String Interpolation

If you don’t want to use objects or strings, you can use inline styles with String Interpolation instead. The benefit of using String Interpolation is when values change, they are dynamically updated. Unlike using strings or objects where object properties are not individually observed, String Interpolation values are.

If color for example in the below example changes its value, the updated value is reflected on your element in the view right away. This allows you to create elements that have style values which react to changes. I built a custom colour picker component which shows the currently selected colour in a square using this technique.

Conclusion

Look at you now, baby: you’re binding with style.