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

Share this video with your friends

Social Share Links

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 $event.target.value.

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 $event.target.value.

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

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today