Call apex method on button click in lwc

Find steps to call apex method on click of a button in the salesforce lightning web component framework.

  1. displayContactsOnButtonClick.html – to display a button on the user interface
  2. displayContactsOnButtonClick.js-meta.xml – to define metadata values for a component
  3. displayContactsOnButtonClick.js – client-side logic to get records from server and display
  4. LwcController.cls – server-side logic to retrieve records

displayContactsOnButtonClick.html

<template>
    <lightning-card title="Display Contacts on click Of Button" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <p class="slds-m-bottom_small">
                <lightning-button label="Get Contacts" onclick={handleGetContacts}></lightning-button>
            </p>
           <template if:true={contacts}>
           <template for:each={contacts} for:item=cont>
                <h4 key={cont.Id}>{cont.AccountId}</h4>
                <h4 key={cont.FirstName}>{cont.FirstName}</h4>
                <h4 key={cont.LastName}>{cont.LastName}</h4>
                <h4 key={cont.Email}>{cont.Email}</h4>             
           </template>
           </template>
           <template if:true={error}>
            {errorMsg}
        </template>
        </div>
    </lightning-card>
</template>


displayContactsOnButtonClick.js-meta.xml

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


displayContactsOnButtonClick.js

import {LightningElement,wire,track} from 'lwc';
import getContactList from '@salesforce/apex/LwcController.getContactList';
export default class DisplayContactWhenButtonClick extends LightningElement {
    @track contacts;
    @track errorMsg;

    handleGetContacts(){
        getContactList()
        .then(result =>{
            this.contacts = result;
        })
        .catch(error =>{
            this.errorMsg = error;
        })
    }
}

LwcController.cls

public with sharing class LwcController {
// Retrive list of contact list
@AuraEnabled
    public static List<Contact> getContactList() {
        return [SELECT Id,AccountId, FirstName,LastName,Email,Phone FROM Contact limit 10];
    }
}


User interface

Lightning web component with a button


Display records on click of a button

Lightning web component with a button and records


You may also like