Sub topic 1
Quick refresher: binding properties in a template
Prerequisites
This chapter assumes the following:
- You can read basic HTML and modern JavaScript, including ES modules, classes, and getters.
- You know a Lightning Web Component (LWC) has an HTML template file and a JavaScript class file with the same base name.
- You have seen curly braces in a template, such as
{name}, and an event handler such asonclick={handleClick}. - You know that a class field is a variable declared on the component class, such as
count = 0;.
This chapter does not teach conditional rendering. It reviews the binding model that lwc:if, lwc:elseif, and lwc:else build on. Every conditional directive reads a value from the component through the same binding syntax.
What binding means
Data binding connects a template to values on the component class. You write a name inside curly braces, and the framework looks up that name on the component instance when it renders.
<template>
<p>Hello, {name}!</p>
<p>Clicked {clickCount} times.</p>
<button onclick={handleClick}>Click me</button>
<input type="text" value={name} onchange={handleNameChange}>
</template>import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
name = 'World';
clickCount = 0;
handleClick() {
this.clickCount += 1;
}
handleNameChange(event) {
this.name = event.target.value;
}
}The example uses three kinds of binding:
- Text binding:
{name}inside an element body inserts the value as text. - Attribute binding:
value={name}sets an attribute or property from the field. In an attribute, you write the braces with no quotes around them. - Event binding:
onclick={handleClick}registers a method as a listener. You pass the method itself, so you do not call it with parentheses.
What can go inside the braces
LWC templates do not evaluate JavaScript expressions. Inside the braces you can put a property name, or a dotted path to a property on an object. Anything more complex has to move into the class.
| Template code | Allowed | Reason |
|---|---|---|
| `{name}` | Yes | Simple property reference |
| `{user.address.city}` | Yes | Dot notation on an object |
| `{count + 1}` | No | Arithmetic is an expression |
| `{isOpen ? 'Yes' : 'No'}` | No | Ternary is an expression |
| `{!isOpen}` | No | Negation is an expression |
| `{formatDate(today)}` | No | Function calls are not allowed |
This restriction is the main reason the next chapters introduce getters. The lwc:if directive accepts the same kind of simple reference as {name}. It does not accept a comparison such as status === 'error' or a negation such as !isOpen. You will compute such values in JavaScript and bind the result.
Computed values with getters
A getter is a method declared with the get keyword. Templates use it exactly like a field. The framework calls the getter during rendering.
<template>
<p>Shouted: {shout}</p>
<p>Characters: {nameLength}</p>
</template>import { LightningElement } from 'lwc';
export default class Shouter extends LightningElement {
name = 'world';
get shout() {
return this.name.toUpperCase() + '!';
}
get nameLength() {
return this.name.length;
}
}A getter has no parentheses in the template. Write {shout}, not {shout()}. Because a getter reads other fields, it produces a new value whenever those fields change and the component re-renders.
Keep getters free of side effects. The framework may call them many times, and a getter that changes state or makes a request will behave unpredictably.
How a change reaches the screen
A component re-renders when a field that the template used during its last render changes. The cycle looks like this.
This cycle is the foundation of conditional rendering. A branch appears or disappears because a field changed, the template re-read it, and the framework added or removed the matching DOM nodes.
Which changes are detected
Since the Spring '20 release, every class field is reactive. The framework detects a change when you assign a new value to the field. Detection depends on what the field holds:
- Primitives (strings, numbers, booleans): any assignment with a different value triggers a re-render.
- Objects and arrays: reassigning the field triggers a re-render. Changing a property inside the object, or pushing onto the array, does not, unless the field is decorated with
@track.
import { LightningElement } from 'lwc';
export default class Profile extends LightningElement {
user = { name: 'Ada', role: 'Admin' };
// Does NOT re-render: the field still points to the same object.
renameInPlace() {
this.user.name = 'Grace';
}
// Re-renders: the field now points to a new object.
renameByReplacing() {
this.user = { ...this.user, name: 'Grace' };
}
}Replacing the object is the preferred pattern. It keeps the code simple, and it avoids the cost of deep observation that @track adds. A bound property such as {user.name} still works, but only a reassignment of user refreshes it.
Public properties with @api
A field decorated with @api is a public property. A parent component can set it through an attribute, and the child reads it with the same {propertyName} binding.
<template>
<p>Welcome, {username}.</p>
</template>import { api, LightningElement } from 'lwc';
export default class WelcomeBanner extends LightningElement {
@api username = 'guest';
}A parent uses it like this:
<template>
<c-welcome-banner username={currentUser}></c-welcome-banner>
</template>Two details matter here:
- An attribute name in a parent template uses kebab-case for multiword properties. A property named
firstNameis writtenfirst-namein HTML. - A child must not reassign a value it received through
@api. Data flows down from parent to child. When the child needs to report something, it dispatches an event and the parent updates its own field.
When the parent changes currentUser, the child re-renders with the new username. A conditional directive in the child would respond the same way.
Putting it together: a toggle you will soon replace
Here is a small component that uses everything above. It toggles a boolean field and shows a label computed by a getter.
<template>
<p>Panel is {stateLabel}.</p>
<button onclick={handleToggle}>{buttonLabel}</button>
</template>import { LightningElement } from 'lwc';
export default class PanelToggle extends LightningElement {
isOpen = false;
get stateLabel() {
return this.isOpen ? 'open' : 'closed';
}
get buttonLabel() {
return this.isOpen ? 'Close' : 'Open';
}
handleToggle() {
this.isOpen = !this.isOpen;
}
}This component binds {stateLabel}, so the text changes, but the paragraph and the button always exist in the DOM. Only their text changes. The next chapters show how to use the same isOpen field to decide whether an entire block of markup exists at all. That is conditional rendering.
Common binding mistakes
- Quoting a binding:
value="{name}"passes the literal text{name}in some contexts and is rejected in others. Writevalue={name}. - Calling a method in the template:
onclick={handleClick()}is invalid. Pass the method name only. - Writing an expression:
{count + 1}does not compile. Add a getter instead. - Reading a non-existent property:
{nmae}renders nothing, because an undefined value displays as empty. A typo does not raise an error, so check the spelling when a value is missing. - Mutating in place: changing a property inside an object field does not re-render, as shown earlier.
What to carry forward
Three points from this chapter apply to every later chapter:
- A template can only reference properties and getters by name. It cannot evaluate expressions.
- A re-render happens when a field the template used is reassigned.
- Getters are the standard way to turn raw state into a value the template can bind.
Exercise
A component has the field items = [] and a template that displays {itemCount}, backed by get itemCount() { return this.items.length; }. A handler runs this.items.push('apple');. The screen still shows 0. Why, and how do you fix it?
Show answer
The handler mutates the array in place. The field items still points to the same array, so the framework sees no reassignment and does not re-render. Fix it by assigning a new array, for example this.items = [...this.items, 'apple'];. The re-render then calls the itemCount getter again, and the screen shows 1.
Exercise
Which of these bindings is invalid in an LWC template, and what is the standard fix? (a) {user.name} (b) {isOpen ? 'Yes' : 'No'} (c) onclick={handleSave}
Show answer
Binding (b) is invalid because a ternary is an expression, and templates accept only property references. Move the logic into a getter, such as get openLabel() { return this.isOpen ? 'Yes' : 'No'; }, and bind {openLabel}. Bindings (a) and (c) are valid: (a) is dot notation on an object, and (c) passes a method as an event listener.