function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
balakumaran Ramanujambalakumaran Ramanujam 

how to call a apex method when the button clicked in LWC

Maciej Król 28Maciej Król 28
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_call_imperative
mukesh guptamukesh gupta
Hi Ramanujam,

Please use below code:-

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(){  // button click event 
        getContactList() // Apex class method
        .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];
    }
}



if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh