Sub topic 1
How a Component's Template and Class Fit Together
A Lightning Web Component (LWC) is a pair of files that work as one unit. The HTML template describes what appears on screen. The JavaScript class holds the data and behavior behind it. This chapter explains how the two connect, what the framework does with them, and which mistakes come from misunderstanding that link. Later chapters build on this: getters, conditions, lists, events, and parent-child data flow.
Prerequisites
This chapter assumes you have:
- Basic HTML and modern JavaScript, including classes, arrow functions, and template literals.
- Some familiarity with creating a Lightning Web Component bundle: a folder with an HTML file, a JavaScript file, and a meta XML file.
You do not need to know decorators, getters, or events yet. They appear in later chapters.
The bundle: three files, one name
Every component lives in a folder called a bundle. The folder name, the HTML file name, and the JavaScript file name must all match. For a component named hello, the bundle looks like this:
| File | Purpose |
|---|---|
| `hello/hello.html` | The template. It declares the markup and the bindings. |
| `hello/hello.js` | The class. It holds the data and the logic. |
| `hello/hello.js-meta.xml` | The configuration. It says where the component can be used. |
The framework pairs the template and the class by name. You never write an import statement for the template. If the HTML file is missing or named differently, the component has no template and renders nothing.
Here is a minimal meta file. It is configuration only and does not take part in binding:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>The template
A template is an HTML file whose outermost element is <template>. Everything the component renders sits inside it.
<!-- hello.html -->
<template>
<p>Hello, {greeting}!</p>
</template>Three rules apply here:
- The file has exactly one root
<template>element. - The text
{greeting}is a binding. The curly braces tell the compiler to look up a name on the component class and insert its value. - The rest is ordinary HTML. The
<template>root produces no element in the page. Only its contents are rendered.
The class
The class supplies the values that the template uses.
// hello.js
import { LightningElement } from 'lwc';
export default class Hello extends LightningElement {
greeting = 'World';
}The requirements for the class are:
- It extends
LightningElement, which is imported from thelwcmodule. - It is the default export of the file.
- It is named in PascalCase. The class
Hellomatches the folderhello. A bundleorderSummarywould hold a classOrderSummary.
greeting = 'World'; is a class field. The template can bind to it by writing {greeting}. With these two files in place, the component renders Hello, World!.
How the link works
The template is compiled ahead of time into a JavaScript function that produces the page content. At render time the framework runs that function with the component instance as its context. Each {name} in the template becomes a read of this.name on that instance.
The flow looks like this:
Several consequences follow from this model.
The template reads from the instance, not from the file
The template never sees the source text of your class. It sees a live object. If the object's greeting is 'World' at render time, the page shows World. If the value changes later and the framework detects it, the template renders again with the new value. Chapter 4 covers what counts as a detectable change.
Direction of data
The flow is one way. The class provides values and the template displays them. Binding {greeting} does not let the user edit greeting by typing in the page. To get user input back into the class, you attach an event handler. A later chapter covers that pattern.
Any member name can be bound, but only by name
The binding looks up a name on the instance. That name can be a field, a getter, or a public property. A plain method is not called by a binding. Writing {formatName()} does not work, and the template cannot take arguments. The chapter on template limits explains why. For now, remember that a binding is a name lookup, not a code expression.
You can use dot notation to reach into an object. If the class has contact = { name: 'Ada' }, the template can write {contact.name}. You can follow a chain of properties, but you cannot add operators, comparisons, or calls.
Where each kind of code belongs
A useful habit is to keep a clear split between the two files.
| Belongs in the template | Belongs in the class |
|---|---|
| Structure, layout, static text | Data and initial values |
| Names to bind to, such as `{greeting}` | Logic that computes values |
| Directives such as `lwc:if` and `for:each` | Event handler methods |
| Attribute bindings, such as `value={name}` | Anything that needs an operator or a function call |
If you catch yourself wanting to put logic in the template, the answer is almost always a getter in the class. Getters are introduced later in this tutorial.
Binding in attributes
Bindings work in attribute values as well as in text. The syntax is the same, but there are no quotes around the braces:
<template>
<lightning-input label="Your name" value={greeting}></lightning-input>
</template>Write value={greeting}, not value="{greeting}". Static attributes such as label="Your name" keep their quotes because they are plain strings and not bindings.
Edge cases and common errors
These are the problems learners most often hit in the first hour.
Misspelled names produce no error
If the template writes {greting} and the class defines greeting, the page renders Hello, !. The binding evaluates to undefined, and undefined displays as empty text. There is no visible warning in the page. When text is missing, check the spelling and capitalization first. Names are case sensitive, so {Greeting} and {greeting} are different bindings.
File names and class names must agree
A bundle hello with a template file named Hello.html, or a folder name that differs from the JavaScript file name, can fail to deploy or load. Keep the folder, the HTML file, and the JavaScript file spelled identically, in camelCase.
Using the component in markup
Once the bundle exists, another component's template can use it as a custom element. The folder name in camelCase becomes a tag in kebab-case with the c- namespace prefix. For the hello bundle, the tag is <c-hello>. For a bundle named orderSummary, the tag is <c-order-summary>. Use a closing tag, as in <c-hello></c-hello>. Self-closing custom tags are not valid in LWC templates.
Fields set in the class body versus in methods
A field declared in the class body, like greeting = 'World';, exists before the first render. A value assigned only later, for example in a method that runs after a click, does not exist at first render. Until then the binding shows nothing. Give every field you bind to an initial value, even an empty string, so the first render is predictable.
Do not rely on the template for private state
The template can read any field on the class, public or not. That does not make private fields visible to other components. Code outside the component cannot read them. Only fields marked with @api can be set by a parent. Chapter 11 covers that.
A small mental checklist
Before moving on, check that you can answer these questions about any component you meet:
- Which file defines the values, and which defines the markup?
- For each
{name}in the template, which class member does it refer to? - Does that member have an initial value?
- Does each binding use only a name or a dot path, with no operators or calls?
If all four answers are clear, you understand the component's data flow at the level this tutorial needs.
Summary
A component is a bundle with a template, a class, and a meta file that share one name. The template holds markup and bindings written as {name}. The class extends LightningElement, is the default export, and supplies the values. At render time each binding becomes a read from the component instance. Data flows one way, from class to template, and bindings can only name a member or follow a dot path. Logic belongs in the class.
Exercise
A bundle named priceTag contains priceTag.html with the text Price: {amount}, and priceTag.js with a class that defines price = 9.99;. The page shows Price: and no number. What is wrong, and what are two ways to fix it?
Show answer
The template binds to amount, but the class defines price. The binding evaluates to undefined and renders as empty text, with no error. Fix it either by changing the template to {price} or by renaming the class field to amount. Both files must use the same name, with matching capitalization.
Exercise
Create a component welcome that shows "Welcome, Grace!" using a class field. Give the template and the class. Then say what tag another component would use to place it in its own template.
Show answer
Template, welcome.html: <template><p>Welcome, {userName}!</p></template>. Class, welcome.js: import { LightningElement } from 'lwc'; export default class Welcome extends LightningElement { userName = 'Grace'; }. Another component places it with <c-welcome></c-welcome>. The class is a PascalCase default export that extends LightningElement, and the template binds with {userName} and no quotes.
Exercise
A teammate writes value="{name}" on a lightning-input and {greeting.toUpperCase()} in a paragraph. Which parts break the binding rules from this chapter, and where should the second piece of logic go instead?
Show answer
In the attribute, the braces must not be wrapped in quotes, so write value={name}. A binding can only name a member or follow a dot path, so it cannot call a method such as toUpperCase(). Put that logic in the class, for example in a getter that returns the uppercase text, and bind the template to the getter's name.