Sub topic 7
Binding CSS Classes and Other Attributes
This chapter assumes you can build a basic Lightning Web Component bundle, know what a getter is, and understand that LWC templates bind to properties with { } and do not evaluate expressions. Here you apply those ideas to the class attribute and to other HTML attributes.
Attributes bind the same way as text
Curly braces work in attribute values as well as in text. You bind a property by writing the braces with no quotes around them:
<lightning-input label="Your name" value={name}></lightning-input>The same rule applies to standard HTML attributes such as class, title, disabled, and href. Do not write value="{name}". The quotes turn it into a literal string.
Why class names need a getter
You might expect to write something like this:
<p class="{name ? 'slds-text-color_success' : 'slds-text-color_weak'}">...</p>This does not work. Templates accept only a property reference, so the ternary has no place there. The fix is to compute the whole class string in JavaScript and bind to the getter.
A getter that returns a class string
The Greeter component from the earlier chapters picks a class based on whether the user has typed a name.
<!-- greeter.html -->
<template>
<lightning-input label="Your name" value={name} onchange={handleChange}></lightning-input>
<p class={messageClass}>{message}</p>
</template>// greeter.js
import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
name = '';
handleChange(event) {
this.name = event.target.value;
}
get message() {
return this.name ? `Hello, ${this.name}!` : 'Please enter your name.';
}
get messageClass() {
return this.name ? 'slds-text-color_success' : 'slds-text-color_weak';
}
}When the user types, handleChange reassigns name. The template re-renders, and both getters run again. The paragraph then gets a new text and a new class.
Combining several classes
A getter can return more than one class, separated by spaces. Build the string in a way that is easy to read and does not leave stray spaces or undefined in the output.
get messageClass() {
const base = 'slds-p-around_small';
const tone = this.name ? 'slds-text-color_success' : 'slds-text-color_weak';
return `${base} ${tone}`;
}A static part of the class can stay in the template only if you bind the whole attribute to a getter. You cannot write class="slds-p-around_small {tone}". Mixing literal text and a binding in one attribute is not supported, so put every class in the getter.
Binding other attributes
The same pattern works for any attribute. Compute the value, then bind it.
get isSubmitDisabled() {
return this.name.length === 0;
}
get nameHelp() {
return this.name ? 'Looks good' : 'Enter at least one character';
}<lightning-button label="Submit" disabled={isSubmitDisabled} title={nameHelp}></lightning-button>For a boolean attribute such as disabled, the getter must return a real boolean. Returning the string 'false' is truthy and would still disable the button.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `class="{messageClass}"` with quotes | The braces are treated as literal text | Write `class={messageClass}` |
| `class="base {tone}"` | Mixed literal and binding is not supported | Return the full string from one getter |
| Expression inside braces, such as `{a ? b : c}` | Compile error | Move the logic into a getter |
| Getter returns a string for a boolean attribute | The attribute may be set unexpectedly | Return `true` or `false` |
Exercise
A component has a boolean field isError. You want a <div> to have the classes slds-box slds-theme_error when isError is true, and slds-box otherwise. Write the getter and the template line.
Show answer
JavaScript: get boxClass() { return this.isError ? 'slds-box slds-theme_error' : 'slds-box'; }. Template: <div class={boxClass}>...</div>. The whole class string, including the constant slds-box, comes from the getter, because a template attribute cannot mix literal text with a binding or contain a ternary.
Exercise
A teammate writes <lightning-button label="Save" disabled="{isSaving}"></lightning-button>. What is wrong, and how do you fix it?
Show answer
The quotes around {isSaving} make the value a literal string instead of a binding. Remove them: disabled={isSaving}. Make sure isSaving holds a real boolean.