Call APEX method from LWC, how to call apex method with parameters from LWC?

You are currently viewing Call APEX method from LWC, how to call apex method with parameters from LWC?
calling apex method form lwc

Welcome back to another Interesting and quick Block, Here you will learn how to send data from your LWC to the APEX method. Here we are having the lightning-input and lightning-button

Want to know how to call apex method from lightning web component , watch the video given below which explains the topic in detail .

This video also discusses the mistake beginners make when they try to call apex from the lighting component.

how to call apex method from lwc component

Code

Apex method of class CommonMethods.cls

    @AuraEnabled(cacheable = true)
    public static String getInputFromLwc(String input){ 
        System.debug('Input value '+ input );
        return input;
    }

JavaScript file of Component

import { LightningElement } from 'lwc';
import getInputFromLwc from '@salesforce/apex/CommonMethods.getInputFromLwc'
export default class GetPicklist extends LightningElement {
    textBoxValue = '';
    onTextChage(event) { 
        this.textBoxValue = event.detail.value;
        this.callApexMethod();
    }
    // this method will send data apex method
    callApexMethod(){
		getInputFromLwc({ input: this.textBoxValue })
	} 
}

Suppose that your apex method returns something here is how to get data from the apex method.

 callApexMethod(){
		getInputFromLwc({ input: this.textBoxValue })
        .then(data => {
            console.log('data from apex ',data)
        })
} 

HTML file of Component

<template>
    <div class="slds-card">
        <h1 class="slds-card__header-title slds-align_absolute-center">Call apex from  lwc </h1>
    </div>
    <div class="slds-card">
        <lightning-input name="input field" label='Input' onchange={onTextChage}  placeholder="Type something"></lightning-input>
        <br>
        <lightning-button name="send" label="sendData" onclick={callApexMethod}></lightning-button>
    </div>
</template>

Thank you .

Leave a Reply