Salesforce lightning-datatable with header and footer

Salesforce lightning-datatable with header and footer

lightning-card can be used for header and footer 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,
            AccountNumber, Type 
            FROM Account 
            LIMIT 10
        ];
         
    }
     
}

Lightning Web Component:

HTML:

<template>
    <lightning-card 
        title="Account Records"
        icon-name="standard:account">
        <lightning-datatable
            key-field="Id"
            data={accounts}
            columns={columns}
            hide-checkbox-column
            show-row-number-column>
        </lightning-datatable>      
        <div slot="footer">
            <h6>
                Only 10 Account Records are fetched!!!
            </h6>
        </div>
    </lightning-card>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
export default class sampleLightningWebComponent extends LightningElement {

    accounts;
    error;

    columns = [  
        { label: 'Id', fieldName: 'Id' },
        { label: 'Name', fieldName: 'Name' },
        { label: 'Industry', fieldName: 'Industry' },
        { label: 'Account Number', fieldName: 'AccountNumber' },
        { label: 'Type', fieldName: 'Type' }
    ];  

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

        if ( data ) {

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

        } else if ( error ) {

            this.error = error;
            this.accounts = undefined;
            console.log( 
                'Error occurred',
                JSON.stringify( error )
            );

        }

    }

}

js-meta.xml:

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

Output:

Leave a Reply