Sub topic 5
How the template and class work together
This chapter assumes you can read basic HTML and JavaScript classes, and that you know the file layout from the earlier chapters: greetingCard.html and greetingCard.js sit side by side in one bundle. Here you will see how those two files connect at run time.
The division of labor
The class holds data and behavior. The template describes what the page looks like for the current data. The template never changes data itself. It reads from the class, and it tells the class when the user does something.
Information moves in two directions:
- Class to template: the template reads fields and getters with
{curly}braces. - Template to class: the template attaches event handlers, such as
onclick={handleAdd}, that call methods on the class.
The framework connects the two. When a field the template reads changes, the framework schedules a re-render of the affected markup.
Binding class values into markup
A binding is a pair of curly braces around the name of a class member. There are no quotes around it when it sets an attribute.
<template>
<lightning-card title={cardTitle}>
<p class="greeting">Hello, {name}!</p>
<p>Clicks: {count}</p>
<lightning-button label="Add" onclick={handleAdd}></lightning-button>
</lightning-card>
</template>import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
count = 0;
get cardTitle() {
return `Greeting for ${this.name}`;
}
handleAdd() {
this.count += 1;
}
}This one component shows each of the three kinds of binding:
| Template syntax | Class member | Role |
|---|---|---|
| `{name}` | `@api name` field | Public field. A parent or App Builder can set it. |
| `{count}` | `count` field | Private field. Only the class changes it. |
| `{cardTitle}` | `get cardTitle()` | Computed value, recalculated on each render. |
| `onclick={handleAdd}` | `handleAdd()` method | Event handler. |
In the template you write {name}. In the class you write this.name. The this. prefix belongs only to JavaScript.
No expressions in templates
The braces accept only a property path, such as {name} or {account.Name}. They do not accept calculations, method calls or ternaries. This is a deliberate rule, not a missing feature.
<!-- Wrong: the compiler rejects this -->
<p>{name.toUpperCase()}</p>
<p>{count + 1}</p>Put the calculation in a getter and bind the getter:
get shoutedName() {
return this.name.toUpperCase();
}
get nextCount() {
return this.count + 1;
}<p>{shoutedName}</p>
<p>{nextCount}</p>Getters keep logic in the file where you can unit test it and set breakpoints.
What the template can see
The template can read any field, getter or method on the class, whether or not it has @api. The @api decorator controls only who outside the component can set or read the member. It has no effect on what the template can reach. Use @api when a parent needs access, and leave it off everything else.
Reactivity: which changes trigger a re-render
Every class field is reactive. Assigning a new value to a field that the template uses causes a re-render. In handleAdd, this.count += 1 is an assignment, so the display updates.
The rule differs for objects and arrays. The framework detects reassignment of the field. It does not detect changes made inside the object, unless the field is decorated with @track.
import { LightningElement } from 'lwc';
export default class TodoList extends LightningElement {
items = ['Write tests'];
addWrong() {
// Mutates the array in place. The field itself is not reassigned,
// so the template does not update.
this.items.push('Deploy');
}
addRight() {
// Assigns a new array to the field, which triggers a re-render.
this.items = [...this.items, 'Deploy'];
}
}Prefer the reassignment pattern. It works without @track and makes each change visible in the code.
The re-render is not immediate. The framework batches changes and updates the DOM after your method finishes. Code that reads the DOM right after setting a field sees the old markup. Tests face the same delay, which is why the Jest example at the end of this tutorial returns a resolved promise before checking the output.
Conditionals and lists
Templates use directives for branching and repetition. A directive is a special attribute that controls rendering.
<template>
<template lwc:if={hasItems}>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>Nothing to show.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class ItemList extends LightningElement {
items = [
{ id: 'a1', label: 'First' },
{ id: 'a2', label: 'Second' }
];
get hasItems() {
return this.items.length > 0;
}
}Points to notice:
lwc:iftakes a property or getter, never an expression such asitems.length > 0. That is whyhasItemsexists.- Each element directly inside
for:eachneeds akeythat is unique within the list and stable between renders. Do not use the loop index. - A
<template>tag with a directive renders only its children. It adds no element to the DOM.
Events: the path from template back to class
An on prefix followed by an event name attaches a handler. The value is a method name in braces, with no parentheses.
<input type="text" value={name} onchange={handleNameChange} />handleNameChange(event) {
this.name = event.target.value;
}Two errors are common here:
- Writing
onclick={handleAdd()}fails. You pass the function, and the framework calls it. - Writing
onclick="handleAdd"with quotes treats the value as a plain string.
Handlers run with this bound to the component, so this.count works without arrow-function tricks.
Public properties from a parent
A parent sets an @api field through an attribute on the child tag. The tag name follows the folder name: greetingCard becomes c-greeting-card. Property names convert from camelCase to kebab-case.
<template>
<c-greeting-card name="Ada"></c-greeting-card>
</template>A property such as maxItems becomes the attribute max-items. Setting a public field from outside re-renders the child when the value changes.
A child should treat its @api fields as read-only. If the component needs to change the value, copy it into a private field, or fire an event so the owner updates it.
Reaching into your own rendered DOM
The class can look up elements in its own template. Use this.template.querySelector, not document.querySelector, because the component's DOM is inside a shadow root.
renderedCallback() {
const p = this.template.querySelector('.greeting');
if (p) {
p.focus?.();
}
}The elements do not exist until the first render finishes. connectedCallback runs before that render, so a lookup there returns null. Use renderedCallback for DOM lookups. It runs after every render, so guard any one-time work with a flag.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Value shows blank | Name in braces does not match a class member, or has a different case | Match the spelling and case exactly |
| Compile error on `{a + b}` | Expressions are not allowed | Use a getter |
| List does not update after `push` | In-place mutation of an untracked field | Reassign a new array |
| Parent attribute is ignored | Field lacks `@api`, or the attribute is not kebab-case | Add `@api` and use `max-items` style names |
| Handler never fires | Parentheses or quotes around the handler name | Write `onclick={handleAdd}` |
| `querySelector` returns `null` | Lookup ran before the first render | Move it to `renderedCallback` |
Exercise
A component has the field scores = [10, 20] and a method that runs this.scores.push(30). The template lists scores, but the page does not change. Give two ways to fix it.
Show answer
Reassign the field instead of mutating it, for example this.scores = [...this.scores, 30];. The other fix is to decorate the field with @track, which makes the framework observe changes inside the array. Reassignment is preferred because it needs no decorator.
Exercise
You want the template to show "Total: 15" where the class has price = 10 and tax = 5. Why does <p>Total: {price + tax}</p> fail, and what is the correct approach?
Show answer
Template braces accept only a property path, not an expression. Add get total() { return this.price + this.tax; } to the class and write <p>Total: {total}</p>.
Exercise
A parent writes <c-price-tag currencyCode="EUR"></c-price-tag> and the child's @api currencyCode stays at its default. What is wrong?
Show answer
HTML attributes on a custom component must be kebab-case. The attribute should be currency-code="EUR".