Sub topic 7
Collecting input with lightning-input and friends
This chapter assumes you can read an LWC template and controller, know basic HTML and modern JavaScript, and have a Salesforce org or scratch org to try the examples in. It covers lightning-input and the related input base components. It also covers the event pattern they share.
The input family
lightning-input is one component that renders many kinds of field. The type attribute selects the kind: text, search, number, email, date, checkbox, toggle and others. Related components cover cases that a single input cannot.
| Component | Use it for |
|---|---|
| `lightning-input` | Text, numbers, dates, checkboxes, toggles, search |
| `lightning-textarea` | Multi-line text |
| `lightning-combobox` | Choosing one value from a list |
| `lightning-radio-group` | Choosing one option with all options visible |
| `lightning-checkbox-group` | Choosing several options |
All of them take a label. Do not leave it out, because it gives screen readers a name for the field.
A controlled search field
The template binds value to a field and listens for onchange. This is the same pattern from the card example, shown here without the card.
<template>
<div class="slds-var-p-around_medium">
<lightning-input
type="search"
label="Name"
value={searchKey}
onchange={handleChange}
></lightning-input>
<p class="slds-var-m-top_small">You typed: {searchKey}</p>
</div>
</template>import { LightningElement } from 'lwc';
export default class ContactSearch extends LightningElement {
searchKey = '';
handleChange(event) {
this.searchKey = event.target.value;
}
handleClear() {
this.searchKey = '';
}
}The flow has two halves. The user types, and the component fires change. Your handler copies the new value into searchKey. Because value={searchKey} is bound in the template, setting the field back to '' in handleClear also empties the visible input.
Checkboxes and toggles use `checked`
The most common mistake is reading event.target.value for a checkbox. For type="checkbox" and type="toggle", the state is in checked. The value property holds a label-like string that you set yourself.
<template>
<lightning-input
type="checkbox"
label="Email opt-in"
checked={optIn}
onchange={handleOptIn}
></lightning-input>
</template>import { LightningElement } from 'lwc';
export default class OptInForm extends LightningElement {
optIn = false;
handleOptIn(event) {
this.optIn = event.target.checked;
}
}Built-in validation
Inputs validate themselves from attributes such as required, min, max, maxlength and pattern. Two methods let you control when messages appear. checkValidity() returns a boolean without showing anything. reportValidity() returns a boolean and shows the error messages.
import { LightningElement } from 'lwc';
export default class SignupForm extends LightningElement {
handleSubmit() {
const allValid = [
...this.template.querySelectorAll('lightning-input')
].reduce((valid, input) => input.reportValidity() && valid, true);
if (allValid) {
// Safe to continue, for example call Apex or fire an event.
}
}
}The && valid is placed last on purpose. If valid came first, JavaScript would stop evaluating after the first failure. The later inputs would then never show their errors.
Common errors
- Forgetting
label. The component renders with a missing-label problem, and screen readers cannot name the field. If you want to hide the label visually, usevariant="label-hidden"and keep thelabel. - Using
event.target.valuefor checkboxes, as described above. - Setting
value={searchKey}without anonchangehandler. The field then shows the typed text, but your property never updates. - Querying with
document.querySelector. Inside a component, usethis.template.querySelector, because the shadow DOM hides the template contents fromdocument.
Exercise
A toggle bound with checked={optIn} never changes optIn when the user clicks it. The handler reads event.target.value. What is the fix, and why does it work?
Show answer
Read event.target.checked in the handler. For checkbox and toggle types, the on/off state is in the checked property. value is not the state.
Exercise
In a form with three required inputs, why should the validity loop use input.reportValidity() && valid instead of valid && input.reportValidity()?
Show answer
With valid first, JavaScript short-circuits once valid is false, so reportValidity() is not called on the remaining inputs. Their error messages would not appear. Putting reportValidity() first means every input is checked.