I face an issue with data binding in LWC if I want to use dynamic form. Let's say I have html like this:
<template for:each={data} for:item="item">
<lightning-combobox
key={item.name}
label={item.name}
required={item.isRequired}
placeholder="Select"
options={item.allowedValues}
>
</lightning-combobox>
</template>
and where {data} is JSON object with all data I need for view .
I need to gather all data(values of selected combobox values) and make JSON from it. Is there any data binding possibilities in LWC for such situations?
For now I have found out only opportunity to use:
var selectFields = this.template.querySelectorAll("combobox");
which is not scalable, since I have not only combobox inside template for:each…
Best Answer
To track the values of your
lightning-combobox
and other form components, track the index of each item in thefor:each
template, use thevalue
attribute in the combobox, and handle theonchange
event:In your JS class, assign the value:
If your Javascript object is a Proxy, you may need to do
JSON.parse(JSON.stringify(this.data))
in some fashion in order to be able to directly set the properties as I've illustrated above.See docs on: