1

I have a html table in which there is a lightning-input type checkbox for each row of the table in the child component. On checking the checkbox the row id is passed to the parent component and pushed in to the array. When I uncheck that checkbox the row Id is still present in the array. I want a solution that whenever I check the checkbox the row id is pushed to the array and whenever I uncheck it, the row id should be removed from the array.

Child component code:

HTML

<lightning-input class="input-checkbox" onchange={handleChange} type="checkbox" value={row.Id} data-id={row.Id} </lightning-input>

JS

handleChange(event) {
const customEventCheck = new CustomEvent('childevent', {
detail:event.target.value
});
this.dispatchEvent(customEventCheck);
}

Parent Component Code:

HTML (calling child component)

<template for:each={tableList} for:item={item} >
<child-component key={item.Id} row={item} onchildevent={storeid} >
</child-component>
</template>

JS

@track checkedId=[];

storeid(event){
var rowId = event.detail;
this.checkedId.push(rowId);
}
2

You can send an attribute in event which will tell you whether the checkbox is checked or not like this

const customEventCheck = new CustomEvent('childevent', {
detail:{val:event.target.value,checked:event.target.checked}
});

and in parent based on that value you can add or remove the element

var rowId = event.detail.val;
var checked=event.detail.checked;

if(checked){
this.checkedId.push(rowId);
}else{
    var index = this.checkedId.indexOf(rowId);
this.checkedId.splice(index, 1);
}
1
  • Thanks, it worked – SFDC IN Jul 23 '20 at 9:19
2

As suggested by @User6670 you need to pass the additional attribute to store the checkbox value.

In addition to splice, you can also use the filter method to remove the unchecked record.

storeid(event){
    if(event.detail.checked){
         this.checkedId.push(event.detail.val);
    } else {
         this.checkedId = this.checkedId.filter(rowId => rowId !== event.detail.val);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.