Search code examples
sapui5

How to bind integer Input value to Slider


I want to have a Slider and an Input control, both for one specific value.

The user should be able to use either the input field or the slider to input his value.

If the user changes the value on the Slider, the input field should show the Slider's value. And if the user inputs something in the input field, the Slider should move to the corresponding value.
Currently, I am creating a JSONModel with the value as a property to bind:

let model = new JSONModel({
  valueName: 10
});
settings.setModel(model);

Now, when I am changing the value on the slider, the update of the input field is working fine. But if I'm entering a value in the input field, the Slider does not move to the value.

Why is that so and how do I solve my problem?

<Slider value="{/valueName}" step="10" width="200px" />
<Input value="{/valueName}" type="Number" width="50px" />

Since the given solutions only worked for integer values a follow up question for float values was created here


Solution

  • I was baffled by this at first. The reason appears to be that the value is saving as a string (in spite of you explicitly specifying number or clearly binding the value in the initial model to a numeric value). I checked this by handling the liveChange event off the Input, retrieving the model value of valueName, doing a parseInt on the value and then setting the Slider to that value. This causes the slider to update as I change the Input.

    Controller:

    handleChange: function(){
        var slider = this.getView().byId("slider");
        var val = this.getView().getModel().getProperty("/valueName");
        slider.setValue(parseInt(val));
    }
    

    XML View:

    <Slider id="slider" value="{/valueName}" min="0" max="100" step="10" width="200px" />
    <Input textAlign="Center" value="{/valueName}" type="Number" width="50px" valueLiveUpdate="true" liveChange="handleChange"/>
    

    The caveat was if I wanted to update the slider to, say, 70 I would need to key in the 0 first (as the slider settings as they stand convert the value to min (0) or 10 the moment I type a number - given the correct behaviour of liveUpdate). There are ways to work around this but I thought I'd get you the answer and you can figure out what to do from there.

    Ultimately i think this is a bug. EDIT - this is not a bug - please refer comment by Boghyon below this Answer