Lit-html: controlled elements

Created on 1 Sep 2019  路  4Comments  路  Source: Polymer/lit-html

Why does this allow editing the input value?

const value = "hello world";

html`
<input type="text" .value=${value} placeholder="insert text" />
`

I'd think that unless I setup onChange to affect the value, it would _always_ be "hello world" ?

All 4 comments

This is because value is the data cached in the TemplateResult that is returned in your example as opposed to the current value of <input/>.value. When the render() method is called a second time it will not find any dirty data to update by pushing instructions to the DOM, so the value changed by a user will not be overwritten leaving the internal state of the value property of the <input /> as the current value that the user had input.

To prevent a user's input, you should listen to the input (or similar) event and actually add some validation to the value. Possibly something like:

const value = "hello world";
const validate = (e) => e.target.value = value;
html`
<input type="text" .value=${value} placeholder="insert text" @input=${valdate} />
`

lit-html can really only know about what is in _your_ code. When you know there will be user input to take account for, if your code doesn't account for it, the default results of interactions with the DOM should be expected.

Thanks- I can't seem to find this idea in the documentation though. Specifically, that if there is no "dirty" data, then the default behavior takes over (e.g. in this case - an input element with a certain initial value but not a constant value).

Feel free to close the issue, since you've answered my question (thanks), though I think it's worth noting that the docs could use a bit more explanation on this point.

Oh, spot-on! Closing this since it's a dup :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

abdonrd picture abdonrd  路  4Comments

fopsdev picture fopsdev  路  5Comments

AndyOGo picture AndyOGo  路  3Comments

lastmjs picture lastmjs  路  5Comments

justinfagnani picture justinfagnani  路  3Comments