I have created a multi-select combobox in LWC, passing list of columns to it from the parent components. Its a json which is being passed from parent to child. JSON :
[{"align":"left","columnOrder":4,"label":"Code","name":"code","resize":true,"width":50,"selected":false,"min_width":50},
{"align":"left","columnOrder":5,"editor":{"type":"text","map_to":"text"},"label":"Order Item Name","name":"text","resize":true,"tree":true,"width":250,"selected":true}]
Below is code for the dropdown
<div class="slds-dropdown slds-dropdown_length-5 slds-dropdown_fluid" id="5" onmouseenter={handleMouseEnter}
onmouseleave={handleMouseleave} role="listbox">
<ul class="slds-listbox slds-listbox_vertical" role="presentation">
<template for:each={inputOptions} for:item="option">
<li class="slds-listbox__item" data-selected="false" data-id={option.name} data-value={option.name}
key={option.name} role="presentation" onclick={handleSelection}>
<div class="slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-is-selected"
role="option" aria-checked="true">
<span class="slds-media__figure">
<lightning-icon
class="slds-icon-utility-check slds-current-color slds-listbox__icon-selected slds-icon_container"
icon-name="utility:check" size="x-small">
</lightning-icon>
</span>
<span class="slds-media__body">
<span class="slds-truncate" title={option.label}>{option.label}</span>
</span>
</div>
</li>
</template>
</ul>
</div>
In the JSON, I have an attribute selected, this is being set to true or false from the parent component, what I need to do is whenever the selected is true, only for that value I need to add the slds-is-selected class, else remove it.
In the JS, I am trying to apply below logic
this.inputOptions.forEach((opt) => {
if (!opt.selected) {
let listBoxOptions = this.template.querySelectorAll('.slds-listbox__option');
for (let option of listBoxOptions) {
console.log('inside for loop');
option.classList.remove("slds-is-selected"); // Using this it will remove for all
}
}
});
But since using this.template.querySelectorAll, it returns all, so it will either add or remove all of it. How do I conditionally add/remove for each?