Lightning-datatable element is used to show records as tabular format in lighting web component. By default lightning-datatable support multiple row selection. Recently one of my colleague asked how we can restrict single row selection in lightning-datatable with checkbox not with radio button.
lighting-datatable has property max-row-selection will restrict maximum number of records can be selected. If we set 1 as value then instead of checkbox it will be show radio.
This blog will just restrict single row selection with checkbox in lightning-datatable. Let us handle this use case to restrict lightning-datatable to support single row selection.
Here is code to show data in lightning-datatable. This will support multi row selection.
To restrict for single row selection we have to add an event listener on row selection event. This event handler will restrict row selection. First add row selection event (onrowselection) in the HTML template.
<lightning-datatable key-field="Id"
data={contact}
onrowselection={handleRowSelection}
columns={columns}>
</lightning-datatable>
Add handleRowSelection event handler in JS file. We can use slice to get last selected row and assign updated selected rows in datatable’s selectedRows property.
handleRowSelection = event => {
var selectedRows=event.detail.selectedRows;
if(selectedRows.length>1)
{
var el = this.template.querySelector('lightning-datatable');
selectedRows=el.selectedRows=el.selectedRows.slice(1);
event.preventDefault();
return;
}
}
After this code, lightning data table will only allow single row selection.
Updated JS Code:
Demo:
Reference:
https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable
Related Posts
Generic DataTable in Lightning Web Component
Extend lightning-datatable with file upload element in Lightning Web Component
3 comments
[…] We can restrict single row selection in data table. See our blog Single Row Selection in Lightning Datatable […]
Hi Dhanik, if we select the header of the check box, all the rows are selected, can we stop header of the checkbox to do that? Please reply your feedback.
To anyone asking the same question, a possible way is store the selected row Id in a variable. Then, prevent deselection event in the onrowselection method. May look something like this:
_selectedRowId;
handleRowSelection = event => {
var selectedRows=event.detail.selectedRows;
var el = this.template.querySelector(‘lightning-datatable’);
if(selectedRows.length>1)
{
selectedRows=el.selectedRows=el.selectedRows.slice(1);
this._selectedRowId=selectedRows;
event.preventDefault();
return;
}else if(selectedRows.length==0)
{
selectedRows=el.selectedRows=this._selectedRowId;
e.preventDefault();
return;
}
}
Afterwards, just make sure to preselect a default row from the start and assign it’s id to this._selectedRowId.