Data Binding in Lighting Web Components

Data Binding in Lighting Web Components


Data binding in Lighting Web component is done using {}. It is called expression. Open the project developed in this post.

Replace World with {greeting}. When we add {} in HTML page, it means this is an expression and has to be evaluated. We added a dynamic value to Hello text, so whatever value we store in "greeting" that would be displayed.


greeting variable is declared in js file as shown below. Notice variable declaration is without var word in web component. 


Push the changes and see if you can see your name instead of World.




To make it more dynamic, lets add input element in html file and bind input element with greeting variable.





When you push the changes and look at Input box, it shows the value in greeting variable but it does not reflex changes in input box. In order to reflect changes in text box, lets add change event to input box and copy changes back to greeting variable. Also, add a bit style to it using SLDS class for input elements.

<input type="text" value={greeting} onchange={handleChange} class="slds-input" />


helloWorld.js will look like below:

import { LightningElement } from 'lwc';

export default class HelloWorld extends LightningElement {
greeting='Sanjivani';

handleChange(event) {
this.greeting = event.target.value;
console.log("Greeting: ", this.greeting);
}
}


Now push the changes and observe the console log upon changing the value in input box. Console shows us changed variable value but UI still not reflecting the change.

We need to use one more concept here called "decorator". We need to decorate our greeting variable with "track" decorator to tell UI to change the value whenever value in greeting is changed. We need to add track decorator in import statement in JS file and decorate greeeting varaible with @track as below.


Now if you notice the page, you will see changes are reflected in label.




Now, lets have a Submit button to see updated label. Lets change binding variable for input text and use greeting variable for changes in input box as below.



Push the changes and see how Update button is changing label.


Comments