Sub topic 8
Templates and data binding
This chapter covers how an LWC template connects to its component class. It assumes you know basic HTML, JavaScript classes, and how the browser DOM and event listeners work. It also assumes you have read the earlier chapters on the component bundle and on custom elements. Reactivity (how a changed field updates the screen) and directives (if:true, for:each) have their own chapters. Here the focus is on what a template is, what you can put inside {}, and what the compiler does with it.
What a template is
Every component that renders UI has an HTML file with the same base name as its folder and JavaScript file. The file's root element is <template>. This is the standard HTML <template> element, which the browser does not render on its own. LWC uses it as the container for the component's markup.
<!-- helloGreeting.html -->
<template>
<p>Hello, {name}!</p>
<input type="text" value={name} onchange={handleChange} />
</template>The markup inside the root <template> becomes the content of the component's shadow root. The root <template> tag itself does not appear in the rendered DOM. The class that supplies name and handleChange lives in the matching JavaScript file:
// helloGreeting.js
import { LightningElement } from 'lwc';
export default class HelloGreeting extends LightningElement {
name = 'World';
handleChange(event) {
this.name = event.target.value;
}
}The template and the class form a pair. The template reads from the class, and the class decides what the template can see.
Binding values with curly braces
A pair of curly braces in the template refers to a member of the component class. There are two places you can use them.
- Text content.
<p>Hello, {name}!</p>inserts the value ofthis.nameas text. - Attribute and property values.
value={name}sets thevalueof the input fromthis.name.
Two rules apply to the syntax.
- In an attribute, write the braces without quotes:
value={name}. Writingvalue="{name}"passes the literal string{name}. - The text between the braces is a property name, not a JavaScript expression.
{name}is valid.{name.length}and{item.label}are valid, because they are property paths.{count + 1},{name.toUpperCase()}, and{isOpen ? 'a' : 'b'}are not valid.
Rule 2 is the most common source of confusion for developers who have used other frameworks. LWC templates deliberately contain no logic. If you need a computed value, write a getter in the class.
Computing values with getters
A getter is a class member declared with get. The template reads it exactly like a field.
// greetingBanner.js
import { LightningElement } from 'lwc';
export default class GreetingBanner extends LightningElement {
firstName = 'ada';
lastName = 'lovelace';
get fullName() {
return `${this.firstName} ${this.lastName}`.toUpperCase();
}
get hasName() {
return this.firstName !== '' || this.lastName !== '';
}
}<!-- greetingBanner.html -->
<template>
<h2>{fullName}</h2>
</template>The template uses {fullName}, which calls the getter each time the component renders. Getters are the place for string formatting, arithmetic, comparisons, and anything else that would be an expression in other frameworks.
Getters are also how you produce boolean values for conditionals. A template cannot write {!hasName}, so you define a second getter such as get hasNoName().
Binding events
Event handlers use the same braces but are attached with an attribute whose name starts with on.
<input type="text" value={name} onchange={handleChange} />onchange={handleChange} calls addEventListener('change', ...) on the element and passes the class method handleChange as the listener. A few details matter here.
- The value in braces must be a method name. You cannot pass arguments, so
onclick={handleClick(item)}is invalid. - The handler runs with
thisset to the component instance, sothis.name = ...works without callingbind. - The handler receives the standard DOM
Eventobject. InhandleChange,event.target.valueis the input's current text.
To pass extra data to a handler, put it on the element as a data- attribute and read it from event.target.dataset. Note that dataset converts data-item-id into the property itemId.
<!-- itemPicker.html -->
<template>
<button data-item-id="42" onclick={handleClick}>Select</button>
</template>// itemPicker.js
import { LightningElement } from 'lwc';
export default class ItemPicker extends LightningElement {
handleClick(event) {
console.log(event.target.dataset.itemId); // "42"
}
}One-way binding
LWC data binding flows in one direction, from the class to the template. When name changes, the template updates. Typing in the input does not change name by itself, so the example needs handleChange to copy the input's value back into the class.
This differs from frameworks with two-way binding directives such as v-model in Vue or ngModel in Angular. In LWC the loop is explicit:
- The class field supplies
value={name}. - The user types, and the browser fires
change. handleChangewritesthis.name = event.target.value.- The framework sees the new value and updates the template.
The explicit loop is a few more lines of code, but it is always clear where a value came from.
What counts as a property versus an attribute
When you write value={name} on a native element like <input>, LWC sets the DOM property value, not the HTML attribute. When you write a plain string such as type="text", it is an attribute. The distinction matters for two reasons.
- Setting a property can change the live state of an element in ways that setting an attribute does not. The
valueproperty of an input reflects what the user sees now, while thevalueattribute is only its initial value. - On a child LWC component,
label={text}sets a public property declared with@api. A later chapter covers this in detail.
Some HTML attributes are reflected from property names with different spellings. A template writes class, but a few properties use camel case, for example tabindex is written tabindex in the template and tabIndex in JavaScript. When a value does not appear to bind, check the spelling in the documentation for that element.
What the compiler does with a template
The browser never sees {name} or onchange={handleChange}. The LWC compiler reads each template at build time and turns it into a JavaScript function that creates and updates DOM nodes. During that step it also checks the template, so a name that does not exist as an allowed template syntax is reported as an error before the component runs.
This is why template syntax is limited. A restricted syntax is something the compiler can analyze fully and optimize, while arbitrary expressions would require evaluating code at render time.
At run time, the compiled function reads class members and compares them with the previous render. Only the nodes that depend on changed values are updated. The mechanism that triggers that re-render is covered in the reactivity chapter.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Page shows the text `{name}` or an attribute holds `{name}` | Braces were quoted in an attribute: `value="{name}"` | Remove the quotes |
| Compile error on `{count + 1}` | Expressions are not allowed in templates | Create a getter such as `get nextCount()` |
| Compile error on `onclick={handle(item)}` | Handlers cannot take arguments | Use a `data-` attribute and read `event.target.dataset` |
| Template shows nothing for a value | The class member name is misspelled, or the member is not defined | Check that the name matches exactly, including case |
| Input shows text but the class value never changes | There is no handler copying the value back | Add `onchange` or `oninput` and assign the field |
| Handler fails with `this` undefined | The method was called as a plain function from other code | Keep handlers as class methods bound through the template |
Summary of what is standard
The root <template> element, HTML attributes, and DOM event names are standard web platform features. The {} binding syntax, the restriction to property paths, and the on-prefix handler binding are additions from the LWC compiler. The chapter on standards versus LWC additions covers that boundary in full.
Exercise
A template contains <p>{firstName.toUpperCase()}</p> and fails to compile. Explain why, and write the fix in the component class and template.
Show answer
LWC templates accept only property paths inside braces, not method calls or other expressions. Add a getter to the class: get upperName() { return this.firstName.toUpperCase(); }, and change the template to <p>{upperName}</p>.
Exercise
A text input uses value={name}, but typing in it never changes this.name. What is missing, and why does LWC not do it automatically?
Show answer
A handler is missing. LWC binding is one-way, from class to template. Add onchange={handleChange} (or oninput) and in the class write handleChange(event) { this.name = event.target.value; }.