Stimulus 2.0 values mapping to input text instead of data attribute?

I’m implementing some new features using Stimulus 2.0 (we already use Stimulus in this app)

I’m a bit confused by the Values API. If I want to map a value to a textbox input, I have to store the value in the data attribute, then as the input changes, update the data attribute through Stimulus?

Is there something I’m missing here to just accessing the <input> value directly? I used to use Targets for this with some JS to shuttle the data between the DOM and stimulus but thought Values would solve this.

Not sure if I’m missing something here! Thanks

Hi Gareth,

You’re right, you could access the <input> value directly.

If you’d like to shadow the field’s value in a data attribute on the controller, that’s an extra option. I figure that would be a good idea if, say, the form field inside the stimulus controller is a small React or Vue instance, and you can’t rely on the DOM element of the field in that React or Vue instance surviving a back operation restore (ie. Turbolinks back operation). In this case it makes sense to shadow the field value in the a stimulus values attribute, so you can instantiate that React or Vue instance from that shadowed field value on back operation.

But in other cases, it’s always preferable to read/write to/from the value on the field directly.

At all times, the DOM is the holder of the state with Stimulus controllers.

Hi,

I was going to create a new thread but it seems like it’s similar to what I am trying to accomplish.

Is there any way in Stimulus 2.0 that I can set an initial value for input that’s updating the target ?
Can’t get this working.

<div data-controller="hello" data-hello-name-value="some initial">
    <input type="text" value="tried with data-hello-name-value etc..instead of value=" data-hello-target="name" data-action="input->hello#greet" />
 </div>

Stimulus works fine, when I type something it gets printed in the console (according to the greet() method on stimulus controller), but I can’t get initial value for <input> working. Tried with different data- tags in both <div data-controller controller> and <input> tags.

My controller has targets [“name”] and values {name: String} spcified.

This may be easy, but couldn’t get this done and documentation does not provide such example.

Thanks!

To set the initial value you can do the following in the connect method:

     connect() {
         this.nameTarget.value = this.nameValue;
     }

If you want the nameValue to be updated with whatever in the text box then your greet function can be:

    greet(e) {
        this.nameValue = e.target.value;
    }

If you want the changes to nameValue update the input box you can have

    nameValueChanged() {
        this.inputTarget.value = this.nameValue;
    }

The last one is redundant though if you’re typing in the input box and updating it when the value is changed.

1 Like