[SalesForce] Pass input text value to controller on button click in LWC

I am learning LWC and I want to pass input text value to controller on a button click. Please help.

Please Note:

I can retrieve the value using onchange function on input as below:

<lightning-input type="text" name="input1" label="Enter a Value" onchange={handleInput}> </lightning-input>

But, I want to retrieve text value on button click:

<lightning-button label="Show Value" onclick={showRefreshVal}></lightning-button>

My code so far:

HTML

<template>
    <lightning-card title="">
        <div class="slds-m-around_medium">
            <lightning-input type="text" name="input1" label="Enter a Value" value={parentVal}> </lightning-input>
            <lightning-button label="Show Value" onclick={showRefreshVal}></lightning-button>
        </div>
    </lightning-card>
</template>

JS

import { LightningElement } from 'lwc';
export default class ApiFunction extends LightningElement {
    parentVal;
    showRefreshVal() {
        // eslint-disable-next-line no-console
        console.log("this.parentVal: ", this.parentVal);
    }
}

OUTPUT

this.parentVal: undefined

Expected OUTPUT

this.parentVal: [value typed on input text]

Best Answer

Data binding is one way in Lightning. What you want to do is just ask the component what the value is. Here's an example:

<template>
    <lightning-input label="Demo">
    </lightning-input>
    <lightning-button label="Update Value" onclick={updateText}>
    </lightning-button>
    <hr />
    {outputText}
</template>

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
    @track outputText;
    updateText(event) {
        this.outputText = this.template.querySelector('lightning-input').value;
    }
}

We can grab the lightning input via querySelector, then get the .value from there. You can set a name or other unique attribute to find a specific input from the available inputs if you need to.

Related Topic