Lightning Web Component Datatable

Let us discuss here a simple example of Lightning Web Component Data table.A lightning-datatable component displays tabular data where each column can be displayed based on the data type. For example, an email address is displayed as a hyperlink with the mailto: URL scheme by specifying the email type. The default type is text.

1. Create an apex class 

Create an Apex class that will get all opportunities. Use the below SFDX Command

sfdx force:apex:class:create -n GetAllOpportunities -d force-app/main/default/apex

Here is the code

public with sharing class GetAllOpportunities {
   @AuraEnabled(cacheable=true)
    public static List<Opportunity> getAllOpps() {
        return [SELECT Id, Name ,StageName, CloseDate ,Type ,Probability,Account.Name from Opportunity];
    }
}

2. Create a Lightning Web Component 

Create a Lightning web component using this SFDX command. this web component will display the opportunities in the table.

sfdx force:lightning:component:create --type lwc -n DatatableEx -d force-app/main/default/lwc

Here is the DatatableEx.html code

<template>
    <h2> Data table Example -1</h2>
    <lightning-datatable data={data} columns={columns} key-field="Id">
    </lightning-datatable>
</template>

Here is the DatatableEx.js JavaScript controller code.

import { LightningElement ,api,wire,track} from 'lwc';
import getAllOpps from '@salesforce/apex/GetAllOpportunities.getAllOpps';

export default class DatatableEx12 extends LightningElement {
    @track columns = [{
            label: 'Opportunity name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Stage Name',
            fieldName: 'StageName',
            type: 'text',
            sortable: true
        },
        {
            label: 'Close date',
            fieldName: 'CloseDate',
            type: 'date',
            sortable: true
        }

    ];
    @track error;
    @track data ;
    @wire(getAllOpps)
    wiredOpps({
        error,
        data
    }) {
        if (data) {
            this.data = data;
            console.log(data);
            console.log(JSON.stringify(data, null, '\t'));
        } else if (error) {
            this.error = error;
        }
    }
}

Use this DatatableEx.js-meta.xml configuration file

 

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

3. Push Changes to scratch org

Use the below SFDX command to push the changes to scratch org

sfdx force:source:push

 

Now add this component to record page using lightning app builder and save it. you can able to see the below data table with the list of opportunities.