Sub topic 1
How a Component's Template and Class Fit Together
Prerequisites
Assume you know basic HTML, JavaScript classes, and template literals. You should also know how an LWC bundle groups an HTML template, a JavaScript class, and a metadata XML file.
Template and Class
A Lightning Web Component (LWC) separates presentation from state:
- The HTML template describes what the component renders.
- The JavaScript class stores data and behavior.
- The framework connects them during rendering.
For a component named hello, the files are usually hello.html and hello.js.
<!-- hello.html -->
<template>
<p>Hello, {greeting}!</p>
</template>// hello.js
import { LightningElement } from 'lwc';
export default class Hello extends LightningElement {
greeting = 'World';
}The template reads greeting from the component instance. It does not import the class or call it directly.
Binding Properties with `{ }`
Curly braces create a template binding. A binding displays a JavaScript property or supplies a value to an attribute.
<template>
<p class={messageClass}>{message}</p>
<lightning-input value={name}></lightning-input>
</template>Here, messageClass, message, and name must be available on the component class. When a value used by the template changes, LWC can render the new value.
Why Templates Cannot Contain Expressions
LWC templates allow simple property references, but they do not allow arbitrary JavaScript expressions. This is invalid:
<p>Total: {quantity * unitPrice}</p>Put the calculation in the class instead:
get total() {
return this.quantity * this.unitPrice;
}A getter is a method used like a property. The template can then bind to {total}. This keeps JavaScript logic in the class and keeps the template declarative, meaning it describes the result rather than the calculation.
Reactive Fields: What Triggers a Re-render
A reactive field is a field whose changes can cause the template to render again. Reassigning a primitive value, such as a string or number, is the clearest case:
handleChange(event) {
this.name = event.target.value;
}If the template uses {name}, this assignment causes LWC to update that part of the display. LWC tracks fields that the template has read. A field that is never used by the current template does not need to trigger visible work.
Exercise
Where should you calculate quantity * unitPrice when the template needs to display it?
Show answer
In a JavaScript getter, then bind the template to the getter's name.