Overview
Data binding allows components to respond to user input by updating properties when form values change. This creates interactive, reactive user interfaces.How It Works
ThehelloBinding component demonstrates two-way data binding:
- The
greetingproperty is bound to both the display text and input field value - When the user types in the input field, the
handleChangemethod updates the property - The template automatically re-renders with the new value
Implementation
Key Concepts
Event Handling
Theonchange attribute binds the input’s change event to the handleChange method:
Event handlers in LWC use the
on prefix followed by the event name in lowercase. For example: onchange, onclick, onkeyup.Accessing Event Data
The event handler receives an event object with atarget property:
event.targetreferences the element that triggered the eventevent.target.valuecontains the current value of the input field
Reactive Properties
When you update a property (likethis.greeting), LWC automatically:
- Detects the change
- Re-evaluates all template expressions that reference the property
- Updates the DOM to reflect the new value
What You’ll See
- Initial render shows “Hello, World!” with an input field containing “World”
- As you type in the input field, the greeting text updates in real-time
- Type “Lightning” to see “Hello, Lightning!”
Best Practices
Use
event.target.value carefully: Always verify the event structure matches your expectations, especially with custom components.Next Steps
- Expressions - Compute values from multiple properties
- Conditional Rendering - Show/hide content based on property values
- Iteration - Render lists of data
