Sub topic 7
Binding CSS Classes and Other Attributes
This chapter covers how to bind element attributes in an LWC template, with a focus on CSS class strings. It assumes you can write basic HTML and modern JavaScript (classes, template literals). It also assumes you have created a Lightning Web Component bundle with an HTML file, a JavaScript file, and a meta XML file. You should already know that {property} binds a class property into a template and that templates cannot contain expressions. The previous chapters covered both.
Attributes use the same curly-brace syntax
Text content is not the only place a template can read a class property. Any attribute value can be bound by writing the property in braces, with no quotes around it.
<!-- badge.html -->
<template>
<span class={badgeClass} title={tooltip}>{label}</span>
</template>// badge.js
import { LightningElement } from 'lwc';
export default class Badge extends LightningElement {
label = 'New';
tooltip = 'This item was added today';
badgeClass = 'slds-badge';
}Three rules apply to every bound attribute.
- Write
class={badgeClass}, notclass="{badgeClass}". Quoting the braces makes the compiler treat the value as a literal string, and the compiler reports an error. - The braces hold a single property reference, such as
{badgeClass}or{user.name}. They cannot hold an expression such as{isActive ? 'on' : 'off'}. - When the property changes, the template re-renders and the attribute updates.
Because inline expressions are not allowed, any attribute that depends on a condition needs a getter. This is the same pattern you used for text and conditions, applied to attributes.
Computing a class string with a getter
The class attribute takes one string of space-separated class names. LWC has no object or array syntax for classes, so you build the string in JavaScript. Here is the Greeter getter from the earlier chapter, in isolation:
get messageClass() {
return this.name ? 'slds-text-color_success' : 'slds-text-color_weak';
}The template binds it with class={messageClass}. Each time name changes, the component re-renders, the getter runs again, and the element receives the new string.
This works well when there are two or three states. Once a component has several independent conditions, a ternary on its own gets hard to read. Collect the class names in an array and join them.
// statusPill.js
import { LightningElement, api } from 'lwc';
export default class StatusPill extends LightningElement {
@api status = 'pending';
@api compact = false;
get pillClass() {
const classes = ['slds-badge'];
if (this.status === 'approved') {
classes.push('slds-theme_success');
} else if (this.status === 'rejected') {
classes.push('slds-theme_error');
}
if (this.compact) {
classes.push('slds-m-around_xx-small');
}
return classes.join(' ');
}
}<!-- statusPill.html -->
<template>
<span class={pillClass}>{status}</span>
</template>The base class slds-badge is always present. The theme class depends on status, and the spacing class depends on compact. The getter returns a single string such as slds-badge slds-theme_success.
Why join with a space
join(' ') guarantees exactly one space between names and none at the ends. If you concatenate by hand, as in 'slds-badge ' + extra, an empty extra leaves a trailing space. That is harmless in the browser, but it makes the value harder to test and to compare.
Keep a stable base class
Return the base class every time, and add or omit modifier classes. Returning a completely different string for each state works, but it makes the getter harder to scan and makes it easy to forget the base class in one branch.
Static and dynamic classes cannot be mixed
An attribute value is either a literal string or a single binding. You cannot write class="slds-badge {extraClass}", because the compiler does not interpolate inside a quoted value.
If you need a fixed class plus a dynamic one, you have two choices.
- Include the fixed class in the getter's returned string, as
StatusPilldoes withslds-badge. - Put the fixed class on a wrapper element and the dynamic class on an inner element.
The first choice is almost always better because it keeps the element count down.
Binding other attributes
Any standard HTML attribute can take a bound value in the same way. Common cases are title, href, src, alt, placeholder, data-* attributes, and aria-* attributes.
<!-- profileLink.html -->
<template>
<a href={profileUrl} title={linkTitle} data-user-id={userId}>
<img src={avatarUrl} alt={avatarAlt} />
{displayName}
</a>
</template>// profileLink.js
import { LightningElement } from 'lwc';
export default class ProfileLink extends LightningElement {
userId = 'u-42';
firstName = 'Ada';
lastName = 'Lovelace';
get displayName() {
return `${this.firstName} ${this.lastName}`;
}
get profileUrl() {
return `/profile/${this.userId}`;
}
get linkTitle() {
return `View profile for ${this.displayName}`;
}
get avatarUrl() {
return `/avatars/${this.userId}.png`;
}
get avatarAlt() {
return `Avatar of ${this.displayName}`;
}
}A getter can read another getter, as linkTitle reads displayName. Each one is recomputed when the template re-renders.
Boolean attributes
Attributes such as disabled, checked, hidden, and required are controlled by a boolean value. Bind a property or getter that returns true or false.
<!-- submitBar.html -->
<template>
<lightning-input label="Email" value={email} onchange={handleEmail}></lightning-input>
<lightning-button label="Submit" disabled={isSubmitDisabled}></lightning-button>
</template>// submitBar.js
import { LightningElement } from 'lwc';
export default class SubmitBar extends LightningElement {
email = '';
handleEmail(event) {
this.email = event.target.value;
}
get isSubmitDisabled() {
return !this.email.includes('@');
}
}The getter produces a boolean from the current state. The button is disabled until the address contains an @. Name boolean getters so they read as a question, such as isSubmitDisabled or hasItems. The template then reads clearly: disabled={isSubmitDisabled}.
Note that a negated condition cannot be written in the template. disabled={!isValid} is not valid. Add a getter for the negation, or name the getter after the state you need to bind.
Accessibility attributes
Bound aria-* attributes follow the same rules. Their values are strings, so a getter should return a string, not a boolean, when the attribute expects "true" or "false".
// expander.js
import { LightningElement } from 'lwc';
export default class Expander extends LightningElement {
isOpen = false;
toggle() {
this.isOpen = !this.isOpen;
}
get ariaExpanded() {
return this.isOpen ? 'true' : 'false';
}
get panelClass() {
return this.isOpen ? 'slds-show' : 'slds-hide';
}
}<!-- expander.html -->
<template>
<button aria-expanded={ariaExpanded} onclick={toggle}>Details</button>
<div class={panelClass}>Panel content</div>
</template>Here a click flips isOpen. That field change causes a re-render, and both getters recompute. One state field drives the ARIA attribute and the visible class.
Class binding versus conditional rendering
You now have two ways to hide content: render it conditionally with lwc:if, or keep it in the DOM and toggle a class such as slds-hide. They behave differently.
| Aspect | `lwc:if` | Class toggle |
|---|---|---|
| Element in the DOM when hidden | No | Yes |
| Child components | Destroyed and recreated on each show | Stay alive and keep their state |
| Cost of showing | Creates elements | Changes one attribute |
| Content reachable by assistive tools when hidden | No | Depends on the class used |
| Best for | Content that is large, rarely shown, or expensive to build | Content that toggles often or must keep its state |
Use lwc:if by default. Choose a class toggle when a child holds state you do not want to lose, such as a half-filled form, or when the content flips many times a second.
Dynamic styles
You can also bind the style attribute. It takes a string of CSS declarations, so the same getter approach applies.
<!-- progressBar.html -->
<template>
<div class="track">
<div class="fill" style={fillStyle}></div>
</div>
</template>// progressBar.js
import { LightningElement, api } from 'lwc';
export default class ProgressBar extends LightningElement {
@api percent = 0;
get fillStyle() {
const clamped = Math.min(100, Math.max(0, Number(this.percent) || 0));
return `width: ${clamped}%`;
}
}The getter clamps the value to a range of 0 to 100, so a bad input cannot produce an invalid width. Prefer classes over inline styles when a fixed set of looks is enough. Reserve style for values that are continuous, such as a width or a color that comes from data.
Common mistakes
- Quoting the binding.
class="{cls}"does not evaluate the property. Writeclass={cls}. - Expressions in braces.
class={a ? 'x' : 'y'}anddisabled={!flag}fail to compile. Move the logic to a getter. - Returning an array or object for
class. The attribute needs a string. Join an array before you return it. - Returning
undefinedornullby accident. A getter that reads a missing property can yieldundefinedand drop the attribute. Give the property a default value or guard against it. - Mutating state inside the getter. A getter that pushes to an array or changes a field can cause repeated work, and it breaks the rule that getters have no side effects. Build a local array, as
pillClassdoes, and return a string. - Forgetting that the template only re-renders on observed changes. If a getter reads a value that is not reactive, the class will not update. The earlier chapters on reactivity explain which changes count.
Putting it together
The next component combines a dynamic class, a bound attribute, and a boolean attribute. It is a password field that reports its own strength.
<!-- passwordMeter.html -->
<template>
<lightning-input
type="password"
label="Password"
value={password}
onchange={handlePassword}
></lightning-input>
<p class={strengthClass} aria-live="polite">{strengthLabel}</p>
<lightning-button label="Save" disabled={isSaveDisabled}></lightning-button>
</template>// passwordMeter.js
import { LightningElement } from 'lwc';
export default class PasswordMeter extends LightningElement {
password = '';
handlePassword(event) {
this.password = event.target.value;
}
get score() {
let points = 0;
if (this.password.length >= 8) points += 1;
if (/[A-Z]/.test(this.password)) points += 1;
if (/[0-9]/.test(this.password)) points += 1;
return points;
}
get strengthLabel() {
const labels = ['Too weak', 'Weak', 'Fair', 'Strong'];
return labels[this.score];
}
get strengthClass() {
const classes = ['slds-text-body_small'];
classes.push(this.score >= 3 ? 'slds-text-color_success' : 'slds-text-color_error');
return classes.join(' ');
}
get isSaveDisabled() {
return this.score < 3;
}
}Typing in the field updates password. The change triggers a re-render, and every getter that depends on password runs again. The score getter is small and cheap, so reading it from three other getters is fine. If it did heavy work, you would compute it once in the handler and store it in a field.
The flow looks like this:
Exercise
A component has the fields isError (boolean) and isLarge (boolean). Write a getter named alertClass that always includes slds-notify, adds slds-theme_error when isError is true, and adds slds-text-heading_large when isLarge is true. Then write the template line that binds it to a div. Why can the template not do this with class={isError ? 'slds-theme_error' : ''}?
Show answer
The getter is get alertClass() { const classes = ['slds-notify']; if (this.isError) classes.push('slds-theme_error'); if (this.isLarge) classes.push('slds-text-heading_large'); return classes.join(' '); }. The template line is <div class={alertClass}>...</div>. The inline ternary fails because LWC templates accept only a single property reference inside braces, not expressions, so the logic must live in a getter.
Exercise
A button should be disabled while items is an empty array. A teammate wrote <lightning-button disabled={!items.length}>. Explain why this does not work and write a fix.
Show answer
The braces cannot contain the ! operator or the .length access, because the template allows only a plain property reference. Add get isEmpty() { return this.items.length === 0; } to the class and write <lightning-button disabled={isEmpty}>.