Pre populated selected records in LWC Datatable

by Rijwan Mohmmed
0 comment

Hello folks, today we will discuss the Pre-populated selected records in LWC Datatable. In some scenarios, the selected checkbox for records in Lightning Datatable needs to be auto-populated. There is a key-field attribute in the LWC Datatable tag that is unique for each row in the table, and based on this field only we can populate pre-selected checkboxes in the data table. On loading LWC Datatable, we can set a unique key-field value in the “selected-rows” attribute. We set the value of this attribute in the code according to the requirements.

Also, check this: Vertical Navigation Bar in LWC


Key Highlights :

  1. Checkbox pre-selected on Datatable load.
  2. In LWC Datatable key field should be unique and use the same field values in the pre-selected array.
  3. Use the “selected-rows” attribute in LWC Datatable.

Code :

preselectedLWCDatatable.Html :

	<lightning-card title="Accounts" icon-name="standard:account">
		<div class="slds-m-around_medium">
			<template if:true={data}>
				<lightning-datatable key-field="Id" data={data} columns={columns} selected-rows={preSelectedRows}>
			<template if:true={error}>


import { LightningElement, wire, track } from 'lwc';
import retrieveAccounts from '@salesforce/apex/DataController.retrieveAccounts';

const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Type', fieldName: 'Type' },
    { label: 'Email', fieldName: 'Email__c', type: 'email' },
    { label: 'BillingCountry', fieldName: 'BillingCountry' },

export default class PreselectedLWCDatatable extends LightningElement {
    @track data;
    @track error;
    @track columns = columns;
    @track preSelectedRows = [];

    wiredAccount({ error, data }) {
        if (data) {
   = data;
            data.forEach(currentItem => {

            this.error = undefined;
        } else if (error) {
            this.error = error;
   = undefined;


<?xml version="1.0"?>
<LightningComponentBundle xmlns="">

Output :

pre-populated-selected-records-in-data table-output-techdicer

Reference :

  1. LWC Datatable

You may also like

Leave a Comment