Sub topic 2
Computing Values with Getters in LWC Templates
Assume you know basic HTML, modern JavaScript, and how an LWC bundle contains an HTML template and JavaScript class. A getter is a JavaScript method that is read like a property. Use getters when a template needs a computed value.
LWC templates allow simple property references such as {total}. They do not allow expressions such as {quantity * unitPrice}. Compute the value in JavaScript instead:
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
}<template>
<p>Total: ${total}</p>
</template>In an LWC template, use {total}, not ${total}:
<template>
<p>Total: {total}</p>
</template>The getter runs when the template reads it. Keep getters free of side effects, such as changing fields. Avoid expensive work in a getter because rendering may read it more than once.
Showing and hiding content with `lwc:if`
Conditional rendering displays markup only when a property or getter is truthy. The lwc:elseif and lwc:else branches must follow the initial condition.
get stockMessage() {
if (this.quantity > 0) return 'In stock';
return 'Sold out';
}
get hasItems() {
return this.quantity > 0;
}<template>
<template lwc:if={hasItems}>
<p>{stockMessage}</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>Binding CSS classes and other attributes
Bind an attribute to a simple field or getter. This example computes a CSS class string:
get messageClass() {
return this.quantity > 0
? 'slds-text-color_success'
: 'slds-text-color_error';
}<template>
<p class={messageClass}>{stockMessage}</p>
</template>The same syntax works for supported dynamic attributes, such as title={tooltip}.
Rendering lists with `for:each` and `key`
Use for:each to repeat markup. Each repeated item needs a stable, unique key on the first element inside the loop.
<template>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>Do not use an array index when records have a durable identifier. The key helps LWC match existing DOM elements to data when the list changes.
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 with {total}.