Beginner 20 min read

Data Binding and Directives

By the end of this lesson, you'll be able to:

  • Explain one-way data binding from JavaScript to the template
  • Bind values to both text content and element attributes
  • Explain why LWC template expressions are deliberately restricted

Prerequisites: "Anatomy of a Component"

One-Way Data Binding

<p>Hello, {greeting}!</p>

{greeting} reads a JavaScript class field or getter of the same name. Data flows JavaScript → template, one direction. When the underlying property changes, the template automatically re-renders — the reactivity mechanics behind this are covered fully in the next lesson.

Binding to Text vs. Attributes

<p>{greeting}</p>
<img src={imageUrl} alt={imageAltText}>

The same {} syntax works whether you're binding into text content or into an element's attribute — the target just determines what the bound value is used for.

Why Template Expressions Are Deliberately Restricted

LWC templates only allow simple property or getter references inside {} — not arbitrary JavaScript. You cannot write {price * 1.15} directly in a template. This is a deliberate design choice, for both performance and predictability: any computed or derived value belongs in a getter in your JS class instead.

Why This Matters in Real Projects

Keeping templates purely declarative — no embedded logic — makes them easier to read at a glance, and pushes all real logic into JavaScript, where it's actually testable (Module 14). A component with formatting or calculation logic scattered across its template becomes much harder to reason about as it grows.

Exercise

Explain, as a comment, why writing {price * 1.15} directly inside an LWC template is not supported, and what the correct alternative is.

Show hint

Recall what kinds of expressions template bindings allow.

JAVASCRIPT

Exercise

Challenge: a developer expects that typing into a plain <p>{name}</p> bound element would update the "name" property automatically. Explain why this doesn't happen.

Show hint

Recall which direction LWC data binding flows.

JAVASCRIPT

Data Binding and Directives Quiz

1. Which direction does LWC data binding flow by default?

2. Is {price * 1.15} a valid LWC template expression?

3. The same {} binding syntax can be used for both text content and element attributes.

4. Why does LWC restrict template expressions to simple property/getter references?

5. A developer wants a value to update automatically when a user types into an input. What is required beyond simple binding?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

LWC binds data from JavaScript into the template in one direction only, using deliberately simple expressions — computed values belong in a getter, not inline template logic.