How to Transfer Data from HTML to JS Controller in Lightning Web Components (LWC)
Gaurav Gupta
Certified System Architect | Certified Application Architect | 19X Certified | Trainer | Double Ranger | Blogger
In Lightning Web Components (LWC), there's a challenge when it comes to updating values between the HTML and JS files. Unlike some frameworks, LWC doesn't inherently support two-way binding, where changes in the HTML file are automatically reflected in the JS file and vice versa.
LWC primarily supports one-way binding, meaning changes in the JS file are reflected in the HTML file. However, when you change a value in the UI, accessing that change in the JS controller isn't straightforward, and LWC lacks a built-in feature for this. Custom logic is required to address this issue.
One approach involves creating an event handler for each input control, as shown in the example below:
<lightning-input label='firstName' value={firstName} onblur={firstNameChangeHandler}></lightning-input>
In the corresponding JS file:
firstNameChangeHandler(event){
this.firstName = event.target.value;
}
This method works, but for a UI with numerous controls, it becomes impractical and messy to create individual event handlers for each control.
To streamline the process, a generic event handler can be created. By adding data attributes to controls and utilizing these attributes, values can be updated in the JS controller. Consider the following code snippet:
JS file
领英推荐
import { LightningElement} from 'lwc';
export default class Parent extends LightningElement {
uiControls = {firstname : 'JavaScript' };
controlValueChangeHandler(event) {
let propName = event.target.getAttribute('data-prop-name');
console.log(propName);
console.log(event.target.value);
this.uiControls[propName] = event.target.value;
console.log(this.uiControls);
}
}
Html
<template>
<lightning-card title="Two Way Binding">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small" >
<lightning-input label="First name" value={uiControls.firstname} onblur={controlValueChangeHandler} data-prop-name="firstname"></lightning-input>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
Here, the data attribute data-prop-name is used to specify which property (e.g., firstName or lastName) should be updated in the uiControls object. This approach allows for a dynamic and cleaner way to handle updates when dealing with multiple controls in the UI.
Output