[SalesForce] LWC Data binding in dynamic form (with template for:each)

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 the for:each template, use the value attribute in the combobox, and handle the onchange event:

<template for:each={data} for:item="item" for:index="index">
   <lightning-combobox
       key={item.name}
       data-index={index}
       label={item.name}
       required={item.isRequired}
       placeholder="Select"
       options={item.allowedValues}
       value={item.myPropertyValue}
       onchange={handleChange}>
   </lightning-combobox>
</template>

In your JS class, assign the value:

@track data;

handleChange(event) {
  this.data[event.target.dataset.index].myPropertyValue = event.target.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:

Related Topic