Moss
Moss

Reputation: 3813

binding class to $el.value in Alpine.js

OK, I'm just playing around with Alpine in Codepen, getting the hang of things, but I can't figure out what I am doing wrong here. With this example input, when I click on it, it correctly logs the value in the text box. If I put a different variable in the :class attribute it works fine. But I can't get it to apply classes based on what I type in the text box. I suppose there is no real-world use for this, but I want to understand what I am getting wrong.

<input type="text" :class="$el.value" @click="console.log($el.value)" />

Upvotes: 0

Views: 2624

Answers (1)

ptts
ptts

Reputation: 2086

Currently, your textbox is not connected to Alpine's internal state management but handled by the DOM which, by itself, has no concept of "reactivity". Therefore, if you change the element's value, Alpine has no idea that it should "rerender" the component.

From Alpine's documentation:

Alpine is "reactive" in the sense that when you change a piece of data, everything that depends on that data "reacts" automatically to that change.

By itself, the value of a textbox is not reactive, i.e. not connected to Alpine's internal state management. For a textbox value to be connected to an Alpine state variable, you can use the x-model directive.

x-model is two-way bound, meaning it both "sets" and "gets". In addition to changing data, if the data itself changes, the element will reflect the change.

Here is a working example:

<script src="//unpkg.com/alpinejs" defer></script>

<style>
  .red {
    color: red;
  }
  
  .bg-yellow {
    background-color: yellow;
  }
</style>

<input type="text" :class="clsText" x-data="{clsText: 'red bg-yellow'}" x-model="clsText" />

Upvotes: 1

Related Questions