Chapter 3: LWC Tutorial – Templates

Chapter 3: LWC Tutorial – Templates

On October 18, 2022, Posted by , In LWC Tutorial, By , With Comments Off on Chapter 3: LWC Tutorial – Templates

Let’s revise a little, as we learned in vanilla JS we have to follow the below steps to create a web component. 

  • We first create the custom element.
  • We attach shadow DOM to it
  • We clone the template and do all the modifications we want
  • Then we append the template to shadow DOM

Look at the below code snippet (refer to comments in code for better understanding):

But the good thing is we don’t have to worry about all this boilerplate code when it comes to LWC, as the framework takes care of all the code by itself.

We create a simple HTML file with <template> tag.  In this file, we can add standard HTML tags plus add directives which are nothing but special HTML attributes which help us control the DOM behavior for example if:true, if:false, etc

Note: <template> needs to be the first tag in any LWC component

Before we dive into basic directives lets first understand how to bind javascript variables on HTML templates in LWC 

Let’s look at the below points to understand them then we will look at examples.

  • We simply surround any property with braces { } to bind it with javascript property.
  • Properties used in the template should be primitive unless used with special directives like for:each.
  • Moreover, we cant compute any value in the HTML template rather we have to use the getter in the javascript class to return the desired values. 
  • We cant add spaces between braces and property name for example { prop_name }, it will give you irregular output
  • All the properties in LWC are reactive ie as soon the value of property changes, the template re-renders automatically to show you updated value except for arrays and objects. In the case of arrays or objects, we have to use a special keyword ( decorator) @track which tells the framework to look for any changes happening to the property and re-render the template.

Let’s jump into code for each point now

If we look at the below code we have created a property “name” in Javascript.

In the HTML template, we have simply bind the “name” property using braces.

Code

---JS----
import { LightningElement } from "lwc";
export default class Basic1 extends LightningElement {
name = "Mr X";
}
------END -----
------HTML -------
<template> 
Hello Everyone , my name is {name}
</template>
----- END ------

On UI output will come as “Hello Everyone, my name is Mr. X

To look at another example we first need to understand directives and basic events in javascript.

Comments are closed.