Sub topic 2
Binding class properties with { }
This chapter covers how a component's JavaScript class feeds values into its HTML template. It assumes you can read modern JavaScript (classes, template literals) and have already created a Lightning Web Component bundle with an HTML file, a JS file, and a meta XML file. Later chapters cover getters, conditionals, lists, and parent-child data flow. Here the focus is the binding syntax itself and its rules.
The model: a template that reads the class
Every component has two halves. The JavaScript class holds state. The template describes markup. Curly braces connect them: {greeting} in the template means "read the greeting property of this component's class instance and put the result here."
<!-- hello.html -->
<template>
<p>Hello, {greeting}!</p>
</template>// hello.js
import { LightningElement } from 'lwc';
export default class Hello extends LightningElement {
greeting = 'World';
}The template renders Hello, World!. Three details matter here:
- You write
{greeting}, not{this.greeting}. The template is evaluated against the component instance, sothisis implied. - The root of every template is a
<template>element. Its content is what the component renders. - The binding is live. When the component re-renders, the template reads the property again.
What a binding can point to
A binding expression is a reference to a property on the component. That property can be any of these:
- A class field, like
greetingabove. - A getter, which computes a value on demand. Getters get their own chapter.
- A property decorated with
@api, which a parent can also set.
A binding can also use dot notation to reach into an object:
<!-- ownerBadge.html -->
<template>
<p>Owner: {owner.name} ({owner.team})</p>
</template>// ownerBadge.js
import { LightningElement } from 'lwc';
export default class OwnerBadge extends LightningElement {
owner = { name: 'Grace Hopper', team: 'Compilers' };
}Dot notation is the only navigation the template supports. You can follow a chain such as {owner.address.city}, but you cannot compute anything inside the braces. The next chapter explains that limit.
What gets rendered for each kind of value
The template converts the value to text. The result depends on the type:
| Value | Rendered as text |
|---|---|
| String | The string itself |
| Number | The number, for example `4.5` |
| `true` / `false` | `true` / `false` |
| `undefined` or `null` | Nothing (empty) |
| Object | `[object Object]`, which is rarely what you want |
Two consequences follow. A property that has not been set yet renders as empty text, with no error. A misspelled property name also renders as empty text. If a binding shows nothing, check the spelling and capitalization of the name first.
Binding to attributes
Curly braces also work in attribute values. This is how you pass data to HTML elements and to child components.
<!-- statusPanel.html -->
<template>
<lightning-card title={cardTitle}>
<p class="slds-p-around_small">Status: {status}</p>
<lightning-button
label={buttonLabel}
disabled={isLocked}
onclick={handleLock}>
</lightning-button>
</lightning-card>
</template>// statusPanel.js
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
cardTitle = 'Deployment';
status = 'Open';
buttonLabel = 'Lock deployment';
isLocked = false;
handleLock() {
this.status = 'Locked';
this.isLocked = true;
}
}Clicking the button changes status and isLocked. The template re-renders, the text updates, and the button becomes disabled.
This example shows three kinds of attribute binding:
title={cardTitle}andlabel={buttonLabel}pass strings.disabled={isLocked}passes a boolean. When the value istrue, the attribute is present. When it isfalse, the attribute is absent.onclick={handleLock}passes a function. The name afteronis the event name, and the binding points to a method on the class. The method name is written without parentheses, because you are passing the method itself and not calling it.
Do not put quotes around the braces
Write title={cardTitle}, not title="{cardTitle}". With quotes, the compiler treats the value as a literal string and does not bind it. Current versions of the compiler report this as an error. Older ones silently rendered the literal text {cardTitle}. Either way, the fix is to remove the quotes.
Text can mix literal characters and bindings, as in Hello, {greeting}!. Attribute values cannot. An attribute is either a plain string (title="Deployment") or a single binding (title={cardTitle}). If you need a mix, such as Deployment: Open in a title, build the whole string in JavaScript and bind to it. That is the job of getters.
How a template reads names
The template compiler needs to know which names refer to which things. These rules cover the common cases:
- Binding names are case-sensitive.
{Greeting}and{greeting}are different properties. - In a child component's tag, attribute names use kebab-case, and the compiler maps them to camelCase properties. For example,
product-name={selectedName}sets the child'sproductNameproperty. The braces still refer to the parent's own property,selectedName, using its camelCase name. - Standard HTML attributes such as
title,value, anddisabledbind the same way as custom ones. - A component's template can only read what the class exposes to it. Fields and getters on the instance work. Plain variables declared in the module but outside the class, and imports, do not. If you need a module-level constant in the template, assign it to a class field first.
// priceTag.js
import { LightningElement } from 'lwc';
const CURRENCY = 'EUR';
export default class PriceTag extends LightningElement {
// The template cannot see CURRENCY directly, so expose it as a field.
currency = CURRENCY;
amount = 12;
}<!-- priceTag.html -->
<template>
<p>{amount} {currency}</p>
</template>The rendering cycle
A binding is only useful if you know when it updates. The sequence is:
- The framework creates the component instance and runs the class field initializers.
- It renders the template, reading each bound property once.
- When a reactive field changes, it schedules a re-render. Re-renders are batched, so several assignments in one handler lead to one render.
- On re-render, it reads the bound properties again and updates only the parts of the DOM whose values changed.
The diagram shows that data flows in one direction: from the class to the DOM. The DOM tells the class about changes only through events. This is one-way data flow, and a later chapter on event handlers covers it in detail.
Common errors
These are the mistakes you are most likely to meet when starting with bindings.
Binding to a name that does not exist
<p>Hello, {greting}!</p>The output is Hello, !. There is no error, because an undefined property renders as empty text. Check the name against the class.
Trying to write an expression
<p>Total: {quantity * unitPrice}</p>The compiler rejects this. The braces take a property reference, not JavaScript code. The fix is a getter:
// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
}<!-- orderSummary.html -->
<template>
<p>Total: {total}</p>
</template>Quoting the binding
<lightning-input label="Name" value="{name}"></lightning-input>This does not bind name. Write value={name}.
Expecting the input to update the field
<lightning-input label="Name" value={name}></lightning-input>This shows the current value of name and nothing more. If the user types, name in the class does not change. LWC has no two-way binding. To capture the typed text you need an onchange handler that assigns the new value to the field. The event handlers chapter shows this pattern.
Rendering an object directly
<p>{owner}</p>This renders [object Object]. Bind to the specific properties you want ({owner.name}), or build a display string in a getter.
Summary of the rules
{name}in text content reads a property of the component instance. Nothis.prefix.attr={name}in an attribute binds a value to it. No quotes, and nothing else in the value.- Dot notation reaches into objects. Computation, indexing, and function calls do not belong in the braces.
- Undefined and null render as empty text.
- Data flows from class to template. Changes flow back through events.
Exercise
A developer writes <lightning-button label="{buttonLabel}" disabled={isLocked}></lightning-button> and finds that the button label shows the literal text {buttonLabel} (or the compiler reports an error), while disabled works. What is wrong, and how do they fix it? Then, also, the developer wants the label to read Lock (3 items) using the fields count and a fixed word Lock. Why can't they write label={Lock ({count} items)}, and what should they do instead?
Show answer
The quotes around {buttonLabel} turn it into a literal string, so it is not bound. The fix is label={buttonLabel}. An attribute value must be either a plain string or one single binding, so a mixed value such as Lock ({count} items) is not valid. Instead, add a getter such as get buttonLabel() { return Lock (${this.count} items); } and bind label={buttonLabel}.
Exercise
A component has the field owner = { name: 'Ada', team: 'Engines' }. Write the template line that shows Ada (Engines), and say what appears if the class instead has owner = undefined and the template uses {owner.name}.
Show answer
The line is <p>{owner.name} ({owner.team})</p>. If owner is undefined, the template cannot read name from it. The binding does not throw an error and renders as empty text, so use a guard such as lwc:if={owner} around it. The conditional rendering chapter covers that directive.