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
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;
}
}
How the two ways work
Way 1 finds the lightning-input with this.template.querySelector and sets its value property. Way 2 uses the flag setValue to hide the second combobox, set the value, and show it again.
A note about Way 2
LWC combines the changes made in one method into a single re-render. When setValue is set to false and back to true in the same handler, the final value is true, so the element is usually not removed and added again. Binding the value directly is simpler and more reliable.
A simpler approach
<template>
<lightning-combobox label="Country" value={value} options={options} onchange={handleChange}></lightning-combobox>
<lightning-input label="Selected value" value={inputValue}></lightning-input>
</template> import { LightningElement } from 'lwc';
export default class PicklistDemo extends LightningElement {
value = '';
inputValue = '';
get options() {
return [
{ label: 'India', value: 'India' },
{ label: 'USA', value: 'USA' },
{ label: 'Japan', value: 'Japan' }
];
}
handleChange(event) {
this.value = event.detail.value;
this.inputValue = this.value;
}
} Both components read their value from a property, so changing the property updates the screen. No query selector is needed.
FAQ
Do I need @track?
Not for simple values such as strings. Since Spring 20 every field is reactive when you assign a new value.
When is querySelector still useful?
When you must call a method on a child component or read its validity, for example reportValidity().