Reactivity
elements man html/reactivity Read as markdownHow the runtime decides what to update when data changes, and the $ handle
for inspecting a live template from the browser console.
Reactivity in templates follows the normal JavaScript distinction between reference and value semantics:
- Objects and arrays pass by reference. Mutating properties or array entries inside an event handler propagates back to the template.
- Primitives pass by value. A handler cannot mutate the caller's variable directly. Use one of the two patterns below to update a primitive attribute from a handler.
(a) Return-value. Handler returns the new value, template assigns it. Sync, pure transforms.
function trim(value: string): string { return value.trim(); }
<input onblur={() => name = trim(name)}>
(b) Callback. Handler invokes a setter. Async, conditional, or updates more than one attribute.
function onSubmit(form: Form, resetUI: () => void) {
resetUI();
saveUser(form);
}
<form onsubmit={() => onSubmit(form, () => form = empty())}>
Tip: when several primitive attributes change together, you can bundle them
into a single private object attribute. The object passes by reference, so
handlers can mutate fields directly:
<Form (private form: { text: string; tag: string } = { text: "", tag: "" })>
$ in the Browser Console
You can use $ in the browser devtools console to set any of the page's html
template attributes and watch the UI update. $ is the page's html template
attributes object, and assigning to any property goes through the same reactive
pipeline the template uses. This helps with debugging and with exploring page
states without clicking through the UI:
$.title = "new title"; // re-renders the title
$.users = Array(100).fill(...); // re-renders the list with 100 rows
$.error = "out of stock"; // flips into the error state
$.theme = "dark"; // switches the theme
You can jump to any reactive state you can construct, without touching the source or rebuilding.