Sub topic 7
Collecting input with lightning-input and friends
This chapter covers the base components that collect user input. It assumes you can read a Lightning web component (HTML template, JavaScript class, CSS file) and that you know basic JavaScript classes and modules. You also need the overview of base components from the earlier chapters. By the end you should be able to choose the right input component, read its value correctly, and avoid the errors that show up most often.
The family of input components
lightning-input is the general-purpose input. Its type attribute decides what it renders: text, email, number, date, checkbox, toggle, search, file, and more. Several other base components cover cases where a plain input is not enough.
| Component | Use it for | Value property |
|---|---|---|
| `lightning-input` | Text, numbers, dates, checkboxes, toggles, search, files | `value` (or `checked` for checkbox and toggle) |
| `lightning-textarea` | Multi-line text | `value` |
| `lightning-combobox` | Choosing one option from a list | `value` |
| `lightning-radio-group` | Choosing one option with all options visible | `value` |
| `lightning-checkbox-group` | Choosing several options | `value` (an array) |
| `lightning-input-field` | A field bound to a record, inside a record form | Managed by the form |
The first five work with values you manage yourself in JavaScript. lightning-input-field is different. It reads field metadata from the org and lives inside a record form, which a later chapter covers.
How lightning-input works
A lightning-input always needs a label. The label is rendered as a real <label> element tied to the input, which matters for accessibility. If you want to hide it visually, use variant="label-hidden". Do not remove it.
<template>
<lightning-input
type="email"
label="Email address"
value={email}
required
message-when-value-missing="Enter an email address."
onchange={handleEmailChange}
></lightning-input>
</template>Attributes you will use often:
typeselects the kind of input. The default istext.valuesets the current value. Forcheckbox,checkbox-buttonandtoggle, usecheckedinstead.requiredmarks the field as required and shows an asterisk.placeholdershows hint text. It does not replace a label.min,max,step,maxlength,minlengthandpatternset constraints.disabledandread-onlycontrol editing.message-when-value-missing,message-when-pattern-mismatchand similar attributes customize validation messages.
Reading values: change versus input events
The component fires a change event when the user commits a value, which usually means leaving the field or pressing Enter. It fires a commit event for some types such as search and number when the user clears the field or presses Enter. For text typed character by character you can listen to onchange and, for most types, it fires on each edit as well, but the exact timing depends on the type. When you need predictable behavior, test the type you use.
Inside the handler, read the new value from event.target.value. For a checkbox or toggle, read event.target.checked.
<template>
<lightning-card title="Newsletter" icon-name="standard:email">
<div class="slds-var-p-around_medium">
<lightning-input
type="text"
name="fullName"
label="Full name"
value={fullName}
onchange={handleChange}
></lightning-input>
<lightning-input
type="checkbox"
name="subscribe"
label="Subscribe to updates"
checked={subscribe}
onchange={handleChange}
></lightning-input>
<lightning-combobox
name="frequency"
label="Frequency"
value={frequency}
options={frequencyOptions}
onchange={handleChange}
></lightning-combobox>
</div>
</lightning-card>
</template>import { LightningElement } from 'lwc';
export default class Newsletter extends LightningElement {
fullName = '';
subscribe = false;
frequency = 'weekly';
frequencyOptions = [
{ label: 'Daily', value: 'daily' },
{ label: 'Weekly', value: 'weekly' },
{ label: 'Monthly', value: 'monthly' }
];
handleChange(event) {
const { name, type } = event.target;
if (type === 'checkbox') {
this[name] = event.target.checked;
} else {
this[name] = event.target.value;
}
}
}One handler serves three inputs. The name attribute on each element matches a class field, so this[name] updates the right one. Fields declared in a class are reactive in current LWC, so a reassignment re-renders the template. Mutating an object field in place (for example this.form.name = 'x') is not tracked for nested properties unless you replace the object or use @track.
Choosing a selection component
The three selection components differ in how much space they use and how many values they hold.
lightning-comboboxshows a dropdown. It suits long lists and saves space. It holds one value, a string.lightning-radio-groupshows every option. It suits short lists where users benefit from seeing all choices. It holds one value, a string.lightning-checkbox-groupshows every option with several selectable. Itsvalueis an array of strings, andevent.detail.valuereturns the new array.
For these components the new value is in event.detail.value, and event.target.value also works in most cases. Pick one convention and use it across the component.
<template>
<lightning-checkbox-group
name="channels"
label="Contact channels"
options={channelOptions}
value={selectedChannels}
onchange={handleChannels}
></lightning-checkbox-group>
</template>import { LightningElement } from 'lwc';
export default class ChannelPicker extends LightningElement {
selectedChannels = ['email'];
channelOptions = [
{ label: 'Email', value: 'email' },
{ label: 'Phone', value: 'phone' },
{ label: 'SMS', value: 'sms' }
];
handleChannels(event) {
this.selectedChannels = event.detail.value;
}
}Validation
Base input components validate on their own when you set constraint attributes. To check them from JavaScript, call checkValidity() or reportValidity() on the element.
checkValidity()returnstrueorfalseand shows nothing.reportValidity()returns the same result and also displays the error messages.
To validate every input in a form, query them and combine the results.
import { LightningElement } from 'lwc';
export default class SignupForm extends LightningElement {
handleSubmit() {
const inputs = this.template.querySelectorAll('lightning-input');
const allValid = [...inputs].every((input) => input.reportValidity());
if (allValid) {
// Safe to read values and send them to the server.
}
}
}Use every with reportValidity() carefully. every stops at the first failure, so later inputs never display their errors. If you want all errors shown at once, use reduce or a loop that calls reportValidity() on each one:
const allValid = [...inputs].reduce(
(valid, input) => input.reportValidity() && valid,
true
);Here reportValidity() is on the left of &&, so it always runs.
For rules the built-in constraints cannot express, call setCustomValidity('message') on the input. Pass an empty string to clear the error. Then call reportValidity() so the message appears.
Common errors
- Missing label. A
lightning-inputwithoutlabellogs a warning and leaves screen reader users without a name for the field. Always set it. - Using
valuefor a checkbox. A checkbox ignoresvaluefor its state. Bindchecked. - Forgetting to feed the value back. If you set
value={x}but your handler never updatesx, the displayed value can snap back on the next render. Keep a handler that stores the new value. - Wrong combobox options. Options must be objects with
labelandvalue. Passing a plain array of strings renders nothing useful. - Mutating arrays in place. For a checkbox group, assign a new array instead of calling
pushon the existing one. - Querying with
document. Usethis.template.querySelector. The component's DOM is inside a shadow tree, sodocument.querySelectorwill not find it. - Stopping at the first invalid field. As shown above,
everywithreportValidity()hides later errors.
Where input components fit
The input components give you full control. You decide what each value means, when to validate, and where to send the data. That control has a cost: you write the handlers and the validation yourself. When the goal is to create or edit a Salesforce record, lightning-input-field inside lightning-record-edit-form does much of that work for you, including field labels, required rules, and picklist values taken from the org. A later chapter covers it. Use plain input components for search boxes, filters, calculators, and any data that is not a direct record edit.
Exercise
A component has a lightning-input type="checkbox" label="Agree" value={agreed} and its handler does this.agreed = event.target.value. The checkbox does not show the state the user chose. What are the two changes needed?
Show answer
Bind the attribute checked={agreed} instead of value={agreed}, and read event.target.checked in the handler, so this.agreed = event.target.checked.
Exercise
A form validates with [...inputs].every((i) => i.reportValidity()). Users report that when two fields are empty, only the first shows an error. Why does this happen, and how do you fix it?
Show answer
every stops at the first element that returns false, so reportValidity() is never called on later inputs. Call reportValidity() on every input, for example with reduce((valid, i) => i.reportValidity() && valid, true), so each field displays its error.
Exercise
You need users to pick several contact channels from a short list, and you want all options visible. Which base component do you use, and what type is its value?
Show answer
Use lightning-checkbox-group. Its value is an array of strings, and the new array is available in event.detail.value.