HTML:
<template for:each={accdata} for:item="acc">
<lightning-button key={acc.data.Id} class="slds-theme_brand" value={acc.data.Id} variant={buttonVariant} label={acc.data.Name} onclick = {handleClick}></lightning-button>
</template>
JS:
import { LightningElement,wire,api } from 'lwc';
export default class accData extends LightningElement {
accdata;
@wire(getData, {accID: "$recordId" })
accData({ error, data }) {
if (error) {
this.error = error;
} else if (data) {
this.accdata= data.map(item => {
return{
data: item,
buttonVariant: ''
}
});
}
handleClick(event){
let dataSize = this.accdata.length;
this.clickedRec =event.target.value;
let objIndx = this.accdata.findIndex((item => item.data.Id === this.clickedRec));
this.accdata[objIndx].buttonVariant='Brand';
for (let i=0; i<dataSize; i++){
if(i != objIndx){
this.accdata[i].buttonVariant='neutral';
}
}
}
}
when I click the button, since it's in for loop it's changing the variant for all the buttons that are in the loop, instead how can I just change the variant of the selected button in the loop. I have searched all possible blogs nothing helped, any suggestion is really appreciated.
Thanks in advance!
Best Answer
There can be another way to solve your requirement. What you can do is, add one more property
buttonVariant
inacc.data
list after retrieving from server. Yor can adddata-id
property in button. This button data-id can be used to retieve current selected button id, then search that id inacc.data
list and updatebuttonVariant
property. Use thisbuttonVariant
in variant={buttonVariant}.As an example, you can do like this :
Html:
Js Code: