Is it possible to implement the logic – when parent row is selected all its child rows are selected as well with lightning web component and tree grid?
HTML:
<lightning-tree-grid
key-field="name"
data={treeItems}
columns={columns}
onrowselection={setSelectedRows}
expanded-rows={requestExpandRows}
selected-rows={selectedRows}>
</lightning-tree-grid>
JS file:
@api locationId;
@api allPO;
@track data;
@track error;
@track selectedRows = [];
setSelectedRows(){
var selectRows = this.template.querySelector('lightning-tree-grid').getSelectedRows();
if(selectRows.length > 0){
var tempList = [];
var tempListExpanded = [];
selectRows.forEach(function (record){
tempList.push(record.id);
})
this.dataObj.forEach(function (record){
if(tempList.includes(record.id)){
record.items.forEach(function (child){
//tempListExpanded.push(record.id);
tempList.push(child.id);
})
}
})
this.selectedRows = tempList;
//this.requestExpandRows = tempListExpanded;
console.log(this.selectedRows);
}
}
@wire(getTreeGridData, { input: '$myValue', allAccs : '$allPO'})
wireTreeData({
error,
data
}) {
if (data) {
// alert(data);
this.setExpandedRows(data);
var res = data;
var tempjson = JSON.parse(JSON.stringify(data).split('items').join('_children'));
console.log(tempjson);
this.dataObj = data;
this.data = tempjson;
this.setSelectedRows(data);
} else {
this.error = error;
}
}
I wanted to implement something like that.
The problem is onrowselection function has no access to @track variables.. Probably there are different execution contexts.
Is there any workaround how we can make it possible with lwc?
Expected behavior:
Best Answer
I thought I'd provide an additional answer to this thread, since the accepted solution cannot accommodate de-selecting child rows when the parent is de-selected. This solution allows for de-selecting parents, de-selecting children separately from the parent, auto-selecting parents when all children are selected, and auto-deselecting parents when at least one child is deselected.
HTML:
JS: