Sub topic 9
Handling input and one-way data flow
This chapter covers how a component reads what a user types and keeps the display in sync with it. It assumes you can already create a component bundle. It also assumes you know class fields, getters, and { } binding from the earlier chapters, and that you know what makes a field reactive.
One-way data flow
Lightning Web Components bind data in one direction. A value moves from the JavaScript class into the template, and the template never writes it back. There is no equivalent of v-model in Vue or [(ngModel)] in Angular.
When the user types into an input, the component class does not change by itself. The input fires an event, and your handler copies the new value into a field. The field change then causes a re-render. Two separate paths make up a two-way experience:
- Down: the template reads a field through
value={name}. - Up: the input reports a change through an event handler, and the handler assigns the field.
The field is the source of truth. The input is a view of it that can send change requests, and it never owns the data.
A complete example
This example comes from the topic plan. The template shows the current value and wires up the handler.
<!-- greeter.html -->
<template>
<lightning-input label="Your name" value={name} onchange={handleChange}></lightning-input>
<p class={messageClass}>{message}</p>
</template>The class owns the field, the handler, and two getters that derive display values.
// greeter.js
import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
name = '';
handleChange(event) {
this.name = event.target.value;
}
get message() {
return this.name ? `Hello, ${this.name}!` : 'Please enter your name.';
}
get messageClass() {
return this.name ? 'slds-text-color_success' : 'slds-text-color_weak';
}
}The sequence when the user types "Ada" is:
- The input fires a
changeevent. - LWC calls
handleChangewith the event object. The template never calls the handler itself. - The handler assigns
this.name = 'Ada'. Reassigning a class field is always observed, so the component is marked dirty. - On the next render,
messageandmessageClassare read again. They returnHello, Ada!and the success class. - The template updates only the parts that changed: the paragraph text, its
class, and the input'svalueif it differs.
The getters have no stored state. They always reflect the current name, so you never have to update message by hand. This is the main reason to prefer derived values over extra fields.
Wiring a handler in the template
Handler binding has a few fixed rules.
- The attribute is
onplus the event name in lowercase:onchange,onclick,oninput,onblur. - The value is a bare method reference in braces:
onchange={handleChange}. You cannot writeonchange={handleChange()}or pass arguments inline, in line with the no-expressions rule from earlier in this tutorial. - LWC calls the method with the component as
this, so you do not need.bind(this). - The method receives the DOM event. Its
targetis the element that dispatched the event, andcurrentTargetis the element the listener is attached to.
You can use the same pattern with a native element:
<!-- nativeGreeter.html -->
<template>
<label for="nameInput">Your name</label>
<input id="nameInput" type="text" value={name} oninput={handleInput} />
<p>{message}</p>
</template>// nativeGreeter.js
import { LightningElement } from 'lwc';
export default class NativeGreeter extends LightningElement {
name = '';
handleInput(event) {
this.name = event.target.value;
}
get message() {
return this.name ? `Hello, ${this.name}!` : 'Please enter your name.';
}
}A native <input> differs from lightning-input in when it reports changes. The native input event fires on every keystroke. The native change event fires only when the user commits the value, usually on blur or Enter. If you want live feedback with a native element, listen for oninput.
The id in the native example works as intended. LWC rewrites ids at runtime to keep them unique, and it also rewrites the matching for attribute inside the same template.
Sharing one handler between several inputs
A form with five fields should not need five near-identical handlers. Put a data- attribute on each input and use it to pick the field to update.
<!-- nameForm.html -->
<template>
<lightning-input label="First name" data-field="firstName" value={firstName} onchange={handleFieldChange}></lightning-input>
<lightning-input label="Last name" data-field="lastName" value={lastName} onchange={handleFieldChange}></lightning-input>
<p>{fullName}</p>
</template>// nameForm.js
import { LightningElement } from 'lwc';
export default class NameForm extends LightningElement {
firstName = '';
lastName = '';
handleFieldChange(event) {
const field = event.target.dataset.field;
this[field] = event.target.value;
}
get fullName() {
return `${this.firstName} ${this.lastName}`.trim();
}
}data-field becomes event.target.dataset.field in JavaScript. A mistyped attribute value assigns a stray field on the component without any error, and nothing reads that field. Keep the data-field values identical to the field names, and consider checking them against a short list if the form is large.
Reading the value: `event.target.value` or `event.detail.value`
Base components such as lightning-input dispatch a custom event that carries the new value in event.detail.value. For a text input, event.target.value also works, which is why the examples above use it. Some components expose their value only through detail. Examples are lightning-combobox and lightning-checkbox-group. A checkbox also differs, because you read event.target.checked or event.detail.checked instead of value. Check the component's reference page for the event payload before you pick one.
What happens when you skip the handler
Suppose the template has value={name} and no onchange. The user can still type, because the browser edits the input's own text. But this.name never changes, so message stays stale and any other part of the template that reads name stays stale too. The field and the visible input have drifted apart, and a later re-render triggered by some other field can write the old value back to the input.
The opposite mistake is a handler with no value={name} binding. The input then keeps its own state, and the field only receives changes. That works for simple reads. It fails when the component needs to reset or prefill the input, for example this.name = '' after a submit. Without the binding, the input keeps its text.
// resettableGreeter.js (excerpt)
handleSubmit() {
// ...use this.name...
this.name = ''; // clears the input only if the template has value={name}
}Bind both directions whenever the component needs to read and control the value.
Where one-way flow stops
The same rule applies between components. A parent passes data down through public properties, and a child sends information up with events. A child must not modify a value it received through @api. If it needs a different value, it dispatches an event and the owner changes its own field. Later chapters cover the details of @api.
The same rule explains why the handler is the right place for side effects. Getters are not, as the pitfalls chapter explains. Keep the handler short: read the event, assign fields, and call any other methods you need. Put derived values in getters.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The handler never runs | Wrong attribute name, such as `onChange`, or the component fires a different event | Use lowercase `onchange` and confirm the event name in the component docs |
| `Cannot read properties of undefined` in the handler | Reading `event.detail.value` from a native element, whose `detail` is not set that way | Use `event.target.value` for native elements |
| Message does not update | Field was never assigned, or the template binds a different property | Log `this.name` in the handler and compare the property names |
| Input does not clear after reset | Template has no `value={name}` binding | Add the binding |
| A getter result is stale | The getter reads a non-reactive source, such as a plain variable outside the class | Read from class fields only |
Do not assign to `event.target.value` hoping to update the component state. That changes the input's DOM value only. The class field stays unchanged, and the next render can overwrite what you wrote. Assign to a field on `this` instead.Summary of the pattern
- The template reads fields. The input has
value={field}. - The input reports changes through
on…={handler}. - The handler assigns a field.
- Getters derive everything else from fields.
Exercise
A component has value={email} on a lightning-input and onchange={handleChange}. The handler contains event.target.value = event.target.value.trim(); and nothing else. The message below the input uses {email}. What does the message show as the user types, and how do you fix it?
Show answer
The message never changes. The handler writes to the input's DOM value and never assigns this.email, so the field stays at its initial value. Fix it by assigning the field: this.email = event.target.value.trim();. The next render then updates both the message and the input.
Exercise
You have a form with firstName, lastName, and city inputs. Each input has onchange={handleFieldChange}. What do you add to each input, and what does the handler do, so a single method updates the right field?
Show answer
Add data-field="firstName", data-field="lastName", and data-field="city" to the respective inputs, matching the class field names. The handler reads const field = event.target.dataset.field; and assigns this[field] = event.target.value;.