Keep a DOM input and state value in sync with the `x-model` directive in Alpine JS

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson, we see how the x-model directive makes achieving "two-way data binding" effortless in Alpine JS.

We see what it would take to recreate the same functionality with an x-bind directive for the input value, as well as an @input event listener which, thanks to an access to the browser's native events via the $event magic property, sets the state value to $

Simon Vrachliotis: [0:00] We have an input field here. When we start typing a name, we want the value of the inputs to be reflected in the paragraph below. We want to take control over the input value and synchronize it with a piece of state.

[0:13] We'll define an x-data object with the name property set to an empty string. We want this name value to be displayed in our paragraph. We'll set an x-text directive to our <span> element and set it to be the name state. If name is empty, let's maintain the default line of underscores.

[0:33] Here's the cool part. Alpine JS gives us a nifty x-model directive that will keep the input values in the data in sync. If the input value changes, the data is updated. If the data is updated, the input value changes. This is what is called two-way data binding.

[0:53] Without x-model, the way to achieve this would be to bind the input value to the name state with x-bind: value = "name" or the short syntax. We would also need to listen to the @input event so we can update the state accordingly.

[1:10] We can use an event with $, what Alpine JS calls a magic property, to retrieve the native browser event. In this case, we want to set the name to $

[1:25] Now, once again, we have a value kept in sync with the state.