Dynamically set value to lightning-combobox, lightning-input | 2 ways

Dynamically set Value to lightning combobox,
codersbugs: Dynamically set Value to lightning combobox,

In LWC there are multiple ways to dynamically set values to custom or standard components. Here we have discussed two ways to set value to lightning-combobox component and lighting-input. 

Way 1: Is using Query Selector. In the below code we set value to lightning-input by using QuerySelector.

Way 2: With visibility. As you can see in below code we set value to second combobox, which is selected from first combobox. In handleChange method we hide the second combox and set value and then make it visible again.

HTML File

				
					<template>
    <div class="slds-grid slds-card slds-p-around_medium">
        <div class="slds-col ">
            <lightning-combobox
                name="Billing Country"
                label="Billing Country"
                value={value}
                placeholder="Select Billing Country"
                options={options}
                onchange={handleChange} >
            </lightning-combobox>
        </div>

        <div if:true={setValue} class="slds-col slds-p-left_large">
            <lightning-combobox
                data-name="ShippingCountry"
                label="Shipping Country"
                value={value}
                placeholder="Select Billing Country"
                options={options}
                readonly="true"
                class="customClass1">
            </lightning-combobox>
        </div>
    </div>

    <lightning-input      
        label="Status"
        value={value}  
        class="customClass">
    </lightning-input>
</template>
				
			

JS File

				
					import { LightningElement, track } from 'lwc';

export default class PicklistDemo extends LightningElement {
    @track setValue = true;
    value = '';

    get options() {
        return [
            { label: 'India', value: 'India' },
            { label: 'USA', value: 'USA' },
            { label: 'Japan', value: 'Japan' },
        ];
    }

    handleChange(event) {
        this.value = event.detail.value;
        this.template.querySelector('lightning-input.customClass').value = this.value;
        this.setValue = false;
        this.value = this.value;
        this.setValue = true;
    }
}
				
			

Leave a Reply