Salesforce Asked on December 7, 2021
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);
}
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);
}
}
Answered by Rahul Gawale on December 7, 2021
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);
}
Answered by User6670 on December 7, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP