Loading ...

Two-way Data Binding in Aurelia

Aurelia is a modern front-end framework for building applications in JavaScript or TypeScript. One of its most convenient features is its powerful binding system, which allows for both one-way and two-way data binding. In this article, we’ll focus on two-way data binding—how it works in Aurelia, why it’s useful, and some quick examples to get you started.

Two-way data binding refers to the process of automatically synchronizing UI elements with model data and vice versa. When the user updates a form field in the UI, the corresponding property in your model (ViewModel) is immediately updated. When your application logic changes the model property, the UI is automatically updated to reflect the new value—without requiring manual event handlers or extra boilerplate code.

Here is the basic example of using two-way data binding:

So, in this example our ViewModel has two properties, firstName and lastName and a computed property fullName. View binds the value of two input fields to firstName and lastName using .two-way and displays the computed fullName dynamically.

When the user types into either the “First Name” or “Last Name” input, the corresponding property in the ViewModel is updated immediately. Conversely, if something in your code changes firstName or lastName, those changes will reflect in the inputs.

Use two-way binding thoughtfully. While it’s convenient, be sure it’s necessary. If a UI element only needs to display a value without changing it, a one-way binding (.bind defaulting to to-view) is more performant and reduces complexity.

Using value.to-view="firstName" tells Aurelia to update the UI only when the model changes. In other words, the text field will reflect any updates to the firstName property in your ViewModel, but user edits in that text field will not feed back into the model. This makes to-view useful for read-only displays or fields you don’t want the user to modify.