Interpolation and the Four Bindings
A template on its own is static HTML. Greenhouse needs the plant's name, its photo, its watering button and a nickname field to stay in step with the data in the class. Angular calls this data binding, and there are only four shapes to learn.
The rule
Curly braces print; square brackets set; round brackets listen; both do both.
| Syntax | Name | Direction |
|---|---|---|
{{ expr }} |
Interpolation | class → template (as text) |
[prop]="expr" |
Property binding | class → template |
(event)="statement" |
Event binding | template → class |
[(value)]="signal" |
Two-way binding | both |
This lesson takes the first. Interpolation evaluates a template expression and puts the result into the page as text:
<h3>{{ plant().name }}</h3>
<p>Water every {{ plant().everyDays }} days</p>
<p>Next watering in {{ plant().everyDays - daysSince() }} days</p>
<img src="/photos/{{ plant().id }}.jpg" alt="Photo of {{ plant().name }}" />The result is converted to a string. null and undefined show as nothing rather than the word "null". Interpolation also works inside an attribute value, as in the alt above.
A template expression should be quick and free of side effects: read a signal, a property, do simple arithmetic, call a pure method. It may use the class's members, but not globals like window or console. It cannot contain assignments, and it runs every time Angular checks the view, so never make a server call or change state there.
Interpolated text is escaped. If a plant's name is <b>Fern</b>, the learner sees the tags as text; Angular will not turn data into HTML by accident.
The shortcut
Say the braces out loud as "print this". Whatever sits between them should be something you could ask a calculator or a getter, never something that does something. If you catch yourself writing an assignment such as count = 0 inside {{ }}, you wanted an event binding.
What value is needed?
Days left:
everyDaysminus days since last watering.
Drills
Answer fast — trust the rule.
Which binding sends a click from the template to the class?
nickname is a signal holding null. What does <p>{{ nickname() }}</p> show?
Which is a good interpolation expression?
A plant name contains <i>Aloe</i>. What does {{ plant().name }} display?
Remember
- Four shapes:
{{ }}prints,[ ]sets,( )listens,[( )]does both. - Interpolation turns a short, side-effect-free expression into escaped text.
- Trap: putting work (assignments, calls that change state) inside
{{ }}.
