Data Binding in Salesforce Lightning Web Component (LWC)

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

Data Binding In LWC

Hey kid !! I hope you are doing great. If you are salesforce enthusiast and want to learn lightning web component development from basics then you are at the right place.

previously we have discussed the pre-requisites of salesforce lightning web component. From this EPISODE we are going to start back to basics series with this episode.

So let's get started...

What exactly is Data Binding ?

have heard of front end and backend before ? Yes or maybe No. 
No worries let's understand from basics 😊.

Let's have a look at below picture :

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

As you can see in the above picture we have 2 files HTML and JavaScript. When we are talking about web development we consider HTML as front-end and JavaScript as backend (client-side). Although we use CSS also for styling but we can ignore for understanding this concept.

So We actually put the attribute on the front-end as in the above example it is {Name} and the value is coming from the client-side controller i.e. from the javascript file.
So when we define the value for Name in javascript file then it will HTML will read that value from it and display on the page.

Before learning LWC we need to learn some web development basic concepts to understand this flow.

As you can see its empty at the moment, as we have not defined anything in the backend. Just try to understand the flow from below picture.

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

In the above example as you can see when we define the value or via logic then that value will automatically reflect from JavaScript to HTML and display on the screen.
In the above picture, we have defined the value of Name as 'SalesforceKid' and it reflects in the input box of HTML File.

If I conclude all of the above then => Its and communication of front end and backend to display data. A journey from HTML To JavaScript for value/data and similarly CSS to HTML for the styling of your components on the screen. LWC also follows a similar communication pattern.

Now let's get back to Salesforce Lightning Web Components ⚡️.

As we have learned how to set up the VS code in the previous EPISODE we will directly start with creating the new components here.

Let's #Begin 

So there are different type of ways to bind the data in LWC salesforce which we are going to learn as below :

1. How to bind an HTML element to the component ?
2. How to use private property @track for data binding and reflecting on the screen ?
3. How to use JavaScript getter property in LWC ?

Pre-requisites : 
Create a new project with manifest and authorize your org in VS Code. 

Let's begin with one by one above ways :

#DataBinding Type 1
1. How to bind an HTML element to the component ?

STEP 1 :

Press Ctrl+Shift+P (Windows) or Command+Shift+P (Mac) and Hit a command >SFDX: Create Lightning Web Component 

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

and provide a name dataBindingType1.

Once the project is created you can see this file structure on the left panel under the lwc.

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

Like this....

STEP 2 :

In the HTML file write the following code :

dataBindingType1.html :
------------------------------------------------------------
<template>
<div>
Hello, {name} Welcome to salesforceKid
</div>
</template>
------------------------------------------------------------

In the above HTML file, we have written just a simple line in which the value of {name} will be requested from backend i.e. JavaScript file.

Point to be noted here is the simplicity of defining the markup. As you can see, unlike Aura component we don't have to write {!v.name} here. Just put your attribute in curly brackets like {name} and there you go.

Simple and easy right ? 

dataBindingType1.js :
------------------------------------------------------------
import { LightningElement } from 'lwc';

export default class DataBindingType1 extends LightningElement{
name = 'Ajinkya';
}
------------------------------------------------------------

In the above JavaScript, we have just defined the name attribute (same as HTML) and defined the name as 'Ajinkya' that's it.

dataBindingType1.js-meta.xml :
------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
</LightningComponentBundle>
------------------------------------------------------------

To expose our component we need to make isExposed as True we will discuss this in further Episodes.

STEP 3 :

Now to take a preview you have two choices :
1. Add this component to lightning application and take a preview (Just like aura component).
------------------------------------------------------------
<aura:application extends="force:slds">
<c:dataBindingType1/>
</aura:application>
------------------------------------------------------------

2. Install Local development (newly release) setup in vs code to preview your components locally.

To do this just open your terminal in VS code and run below two commands 

command 1 :
------------------------------------------------------------
sfdx plugins:install @salesforce/lwc-dev-server 
------------------------------------------------------------

command 2 :
------------------------------------------------------------
sfdx force:lightning:lwc:start
------------------------------------------------------------

and that's now you can display your preview localhost:3333 port in your browser.

STEP 4 :

now whenever you right-click on the lwc components.

Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid

Once you click on Preview Component Locally you can preview it without adding or deploying to your salesforce org. Isn't it so cool ?

So the output will look like this :
------------------------------------------------------------
Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid
------------------------------------------------------------

As you can see in the first type, In the output Ajinkya is coming from our javascript name = 'Ajinkya'. and it completed the statement as "Hello, Ajinkya Welcome to salesforcekid".

Now let's learn the next cool way of doing the data binding 

#DataBinding Type 2
2. How to use private property @track for data binding and reflecting on the screen ?

In this type, the user will give input and based on that input the javascript will get that value to compute and display the output to the user on HTML again. And the output will dynamically change based on the user input with the help of @track property as this is the private property to reflect the input change on the Screen.

Let's understand by creating a new lwc component :

STEP 1 : 

Create new lwc component from VS code called as dataBindingType2.

STEP 2 :

Create the component with the below code :

dataBindingType2.html : 
------------------------------------------------------------
<template>
<lightning-card title="Data Binding Type 2">
<div class="slds-p-around_medium">
<p style="font-size:50px;font-weight:bold;">Hello !! {name}</p>
<p>This is Data Second Type Of Data Binding in LWC</p>
<br/>
<lightning-input name="Your Name"
label="Enter Your Name"
value={name}
onchange={handleChange}>
</lightning-input>
</div>
</lightning-card>
</template>
------------------------------------------------------------

In the above HTML file, we have a similar structure. only addition with the <lightning-input> tag where we have defined the name(name for input), label (label to display), value (input value), onchange (on changing of input call this function from .js file).

Now here we are using name attribute as input value as well as displaying it on the screen.

Now take look at .js file below :

dataBindingType2.js : 
------------------------------------------------------------
import { LightningElement,track } from 'lwc';

export default class DataBindingType2 extends LightningElement {
@track name = 'Ajinkya';

handleChange(event) {
this.name = event.target.value;
}
}
------------------------------------------------------------

In the above code, we have used @track in front of name variable so that whenever the input value will change it will track the updated value.


in the next line, we have defined the function handleChange(event){}. As you can see how simple it is to define the function here in lwc than aura.

As we are handling onchange HTML event in the javascript with the function, Hence we have written (event) in brackets.

Now in the next line this.name = event.target.value; Oooooo what's this ????

Chill.....let's break it down kid to understand it completely.

this.name : The variable name which we have defined at the beginning, we are just recalling it in the function to assign its changed value.

event.target.value : This means from the onchange event I want the targeted value of value from the <lightning-input value={name}> .
Meaning, Whatever is there in value get that. 

If you want other parameters from the <lightning-input /> tag you can get that as well like for label the syntax will be event.target.label likewise you can use this.

STEP 3 :

And finally time for output.....same as before just right click on your component and hit SFDX: Preview Component Locally or with Lightning Application choice is yours.

It will look like this 

OUTPUT :
------------------------------------------------------------
Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid
------------------------------------------------------------

If you change the default input it will also reflect on place where name is displaying like this :

------------------------------------------------------------
Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid
------------------------------------------------------------

Wohoooo Coool right ?? 🍻 Keep Calm we have one more way of doing this...

#DataBinding Type 3
3. How to use JavaScript getter property in LWC ?

Whenever we want to dynamically calculate the value of property used in HTML Templates then we use the most powerful javascript function getter property.

Advantage of using this is the pain of unit testing and debugging as the outcome coming from this function is already validated in javascript file. So it will save your debugging effort.
Hence whenever your component renders for the first time it also invokes the getters from your JavaScript code.

So let's understand with the help of the example :

STEP 1 :

Create a new lightning web component from the VS code called as dataBindingType3.

STEP 2 :

Create the components with the below codes :

dataBindingType3.html
------------------------------------------------------------
<template>
<lightning-card title="Data Binding Type 3">
div class="slds-p-around_medium">
<p style="font-size:50px;font-weight:bold">Hello !! {name}</p>
p>This is Third Type Of Data Binding in LWC</p><br/>
Your Name and Blog Name is : <strong>{blogname}</strong>
</div>
</lightning-card>
</template>
------------------------------------------------------------

In the above HTML, we want values for {name} and {blogname} from .js file. That's it !! So we need to check the javascript file to understand how these values are actually computing in client-side controller (.js file).

dataBindingType3.js
------------------------------------------------------------
import { LightningElement} from 'lwc';
export default class DataBindingType3 extends LightningElement {
name = 'Ajinkya';
blogName = 'SalesforceKid';
get blogname(){
const completeName = `${this.name} ${this.blogName} `;
return completeName.trim().toLowerCase();
}
}
------------------------------------------------------------

As you can see we declared the name and blogName with predefined values.
Hence whenever your lightning web component loads for the first time it will take these values and display on the screen right ??

The answer is NO !! 

As we know this .js file also contains the get function in it for blogname. Hence when component load for the first time it will take value for name as it is declared 'Ajinkya' BUT for the blog name first it will take the predefined value then it will compute get blogname() function.

In get blogname() function we have defined one const variable called completeName which means the value in it will be constant.

Then `${this.name} $}{this.blogName}` is the concatenation syntax in modern JavaScript 😊 it simply means name + blogName. and return the result in Lower Case. 

The Picture would be more clear with the output. So lets Go...Go...Go.


STEP 3 :

And finally time for output.....same as before just right click on your component and hit SFDX: Preview Component Locally or with Lightning Application.

And the output will be :
------------------------------------------------------------
Data Binding in Salesforce Lightning Web Component (LWC) By SalesforceKid
------------------------------------------------------------

Wooooo !! As you can see, At the place of {name} the output is Ajinkya.
Whereas value at the place of {blogname} we have name + blogname that too in lowerCase.

⚡️That's the power of JavaScript Getter Method to compute and bind the data when component loads.

Hence with these cool 3 ways, we can Bind our data and select the right way based on our requirement.

In the next EPISODE, we will discuss how we can render list of data in Lightning Web Component So stay tuned......Kid 🏃‍♂️

WOHOOO !! YOU HAVE JUST COMPLETED DATA BINDING IN LIGHTNING WEB COMPONENT (LWC) EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 

                                                 NEXT >>

Salesforcekid By Ajinkya Dhas on Play Store
Data Binding in Salesforce Lightning Web Component (LWC) Data Binding in Salesforce Lightning Web Component (LWC) Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.