It's possible to preselect items, however I noticed a bug on API v42 (current version) and I confirmed that with SFDC support team. When using the attribute to bind the selected rows, it simply doesn't work, however if you find the lightning:datatable and then change the selectedRows, it works properly.
component = component.find("partnerTable");
component.set("v.selectedRows", selectedRowsIds);
Please find an example below, I'm creating a mockdata and selecting the first item by the Id.
Component
<aura:attribute name="partnerdata" type="Object" access="private" />
<aura:attribute name="partnercolumns" type="List" access="private" />
<aura:attribute name="partnerSelectedRows" type="List" access="private" default="" />
<!--
<lightning:datatable aura:id="partnerTable" data="{!v.partnerdata}"
columns="{!v.partnercolumns}" keyField="Id" selectedRows="{!v.partnerSelectedRows}"/>
-->
<lightning:datatable aura:id="partnerTable" data="{!v.partnerdata}"
columns="{!v.partnercolumns}" keyField="Id" />
Controller
({
doInit : function(component, event, helper) {
helper.getMockData(component, event, helper);
}
})
Helper
({
getMockData: function(component, event) {
console.log("Load mock data!");
component.set("v.partnercolumns", [{
label: "Name",
fieldName: "Name",
type: "text"
},
{
label: "Status",
fieldName: "status__c",
type: "text"
},
{
label: "Created Date",
fieldName: "createdate__c",
type: "date"
}
]);
component.set("v.partnerdata", [{
Id: "a0319000001GtsjAAC",
Name: "John Doe",
status__c: "Active",
createdate__c: "2005-01-01"
},
{
Id: "a0319000001GtsjAAD",
Name: "Mary Doe",
status__c: "Active",
createdate__c: "2005-02-10"
}
]);
var selectedRowsIds = ["a0319000001GtsjAAC"];
// I was expecting the line below to work
//component.set("v.partnerSelectedRows", selectedRowsIds);
// Workaround to selectRows
component = component.find("partnerTable");
component.set("v.selectedRows", selectedRowsIds);
}
})
Yes, it only works on the checkboxes. Unfortunately, there is no onrowclick type handler as there was in Visualforce right now. If you want to make a Lightning Data Table that has this feature, you're going to have to write your own component(s) to do this.
Best Answer
Create an attribute of type List as a helper attribute to hold old data -- Try the below code...
yourComponent.cmp - add the attribute
On your table selection event add this code ---
In the javaScript code, you will finally have your list of objects which has been unselected. This line -
Hope this will help.