Data Binding in LWC

How to Bind Properties in Template with Properties in Java Script It is important to understand how javascript properties can be accessed in the template. To access any javascript property in template, surround that property with curly braces.

@track property = ''; // in javascript

{property} // in template with no spaces

If a property is changed in template it doesn’t automatically update in javascript. For the javascript property to update we need to create an onchange() event in the template, handle it and change the value of property in javascript.

binding.html

<template> <lightning-card title= "Data Binding" > <div class= "slds-p-around_small" > <lightning-input label= "Enter a value" value= {property} onchange= {handleChange} ></lightning-input> <br></br> {property} </div> </lightning-card> </template>



binding.js

import { LightningElement , track } from ' lwc ' ; export default class Binding extends LightningElement { @ track property = '' ; handleChange ( event ) { this . property = event . target . value ; } }





Using Getters in place of Expressions

To compute a value for a property, use a JavaScript getter. For example, to convert the name to all uppercase letters, use a getter function in the JavaScript class.

Getters are much more powerful than expressions because they’re JavaScript functions. Getters also enable unit testing, which reduces bugs and increases the fun.

Define a getter that computes the value in your JavaScript class.

get propertyName() { }

Access the getter from the template.

{propertyName}

getterFunction.html

<template> <lightning-card title= "Using Getters" > <div class= "slds-p-around_small" > <lightning-input label= "Enter a value" value= {property} onchange= {handleChange} ></lightning-input> <br></br> {upperClass} </div> </lightning-card> </template>



getterFunction.js

import { LightningElement , track } from ' lwc ' ; export default class getterFunction extends LightningElement { @ track property = '' ; handleChange ( event ) { this . property = event . target . value ; } get upperClass () { return this . property . toUpperCase (); } }



Here instead of using property directly, we are using javascript getter function.

Also Read:

Get started with Salesforce lightning web components

Set up your Dev Environment for Building Salesforce Lightning Web Components

Create your First Lightning Web Component

[Salesforce Lightning Web components Editable List](/2019/04/blog-post.html)

If you enjoyed this article, share it with your group!

Subscribe to get the latest updates directly in your inbox.