Disable Button when no rows selected Lighting Data Table in Salesforce Lightning Web Component

Disable Button when no rows selected Lighting Data Table in Salesforce Lightning Web Component

Sample Code:

Apex Class:

public class AccountController {
 
    @AuraEnabled( cacheable = true )
    public static List< Account > fetchAccounts() {
     
        return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ];
         
    }
     
}

Lightning Web Component:

HTML:

<template>      
    <lightning-card title="Accounts" icon-name="custom:custom63">  
        <template if:true={accounts}>      
            <lightning-datatable
                key-field="Id"
                data={accounts}
                columns={columns}
                onrowselection={handleSelected}>
            </lightning-datatable>  
        </template>      
        <template if:true={error}>  
            {error}>                  
        </template>  
        <div slot="footer">
            <lightning-button label="Next" disabled={disableBool}></lightning-button>
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
 
const COLUMNS = [   
    { label: 'Name', fieldName: 'Name' },
    { label: 'Industry', fieldName: 'Industry' }
];

export default class LightningDataTable extends LightningElement {
     
    accounts;
    error;
    columns = COLUMNS;
    disableBool = true;

    @wire( fetchAccounts )  
    wiredAccount( { error, data } ) {

        if ( data ) {

            this.accounts = data;
            this.error = undefined;

        } else if ( error ) {

            this.error = error;
            this.accounts = undefined;

        }

    }

    handleSelected( event ) {
        
        const selectedRows = event.detail.selectedRows;

        if ( selectedRows.length > 0 ) {
            
            this.disableBool = false;

        } else {
            
            this.disableBool = true;
            
        }

    }

}

JS-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply