I have a lightning datatable that i would like to deselect existing selected rows when i cancelled.
When i clicked cancel button, the selectedRows of lightning data table set [].
using cmp.find("ltngCmp").set("v.selectedRows", []);
then again loaded lightning:dataTable the preSelected rows are rendering issue.
POCLtngDataTable.app
<aura:application extends="force:slds">
<aura:attribute name="renderLtngDataTable" type="Boolean" default="false"/>
<aura:attribute name="selectedRecords" type="List" default="[]" />
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<aura:if isTrue="{!v.renderLtngDataTable}">
<lightning:card title="Demo">
<aura:set attribute="actions">
<lightning:button label="cancel" variant="brand" onclick="{!c.cancel}"/>
</aura:set>
<lightning:datatable aura:id="ltngCmp" data="{! v.mydata }"
columns="{! v.mycolumns }"
keyField="Id"
onrowselection="{! c.getSelectedName }"/>
</lightning:card>
<aura:set attribute="else">
<lightning:button label="RenderLtng" variant="netural" onclick="{!c.showLtng}"/>
</aura:set>
</aura:if>
</aura:application>
POCLtngDataTableController.Js
({
init: function (cmp, event, helper) {
cmp.set('v.mycolumns', [
{label: 'Name', fieldName: 'LastName', type: 'text'},
{label: 'Email', fieldName: 'Email', type: 'email'}
]);
var dataRecords = [];
for(var i = 0; i < 5; i++){
var dataRecordObj = {};
dataRecordObj.Id = 'a' + i;
dataRecordObj.LastName = 'kk' + i;
dataRecordObj.Email = 'test'+ i +'@test.com';
dataRecords.push(dataRecordObj);
}
cmp.set('v.mydata', dataRecords);
},
getSelectedName: function (cmp, event) {
var selectedRecords = [];
var selectedRows = event.getParam('selectedRows');
// Display that fieldName of the selected rows
selectedRows.forEach(function(selectedRow){
selectedRecords.push(selectedRow);
})
cmp.set("v.selectedRecords", selectedRecords);
},
showLtng : function(cmp, event, helper){
cmp.set("v.renderLtngDataTable", true);
},
cancel : function(cmp, event, helper){
var ltngCmp = cmp.find("ltngCmp");
if(ltngCmp){
var selectedRows = ltngCmp.get("v.selectedRows");
selectedRows.length = 0;
ltngCmp.set("v.selectedRows", selectedRows);
}
cmp.set("v.renderLtngDataTable", false);
}
})