<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Giorgio Galassi on Medium]]></title>
        <description><![CDATA[Stories by Giorgio Galassi on Medium]]></description>
        <link>https://medium.com/@giorgio.galassi?source=rss-892fd702c871------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zB81voctw5CsHfs7RmrOdw.jpeg</url>
            <title>Stories by Giorgio Galassi on Medium</title>
            <link>https://medium.com/@giorgio.galassi?source=rss-892fd702c871------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:33:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giorgio.galassi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A2UI in Angular: Your Zod Catalog Is the Trust Boundary ️]]></title>
            <link>https://medium.com/@giorgio.galassi/a2ui-in-angular-your-zod-catalog-is-the-trust-boundary-%EF%B8%8F-922a133328a8?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/922a133328a8</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[generative-ui]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 08:39:53 GMT</pubDate>
            <atom:updated>2026-11-16T08:57:04.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vXJGLWIwtuU0qUp4.jpg" /></figure><p>Let’s be honest: the first time you hear “the agent builds the UI”, the reaction is a mix of curiosity and alarm. Curiosity because a form that appears exactly when the conversation needs it is a genuinely new kind of interface. Alarm because the same sentence sounds like “a model decides what runs in my app”.</p><p>With <strong>A2UI</strong> it doesn’t. The agent never sends HTML or code, it sends a description of a UI made of components <strong>you</strong> wrote ( <a href="https://lnkd.in/p/de2yVwb7">here’s one real message</a>, next to the Angular component it becomes), and the thing that keeps that promise is the <strong>catalog</strong>. In this article I’ll walk through the catalog of my AngularDay demo: one Zod schema per component, read by the model, by the agent’s validation and by the Angular component itself.</p><blockquote><em>⚠️ </em><strong><em>Version note:</em></strong><em> A2UI </em><strong><em>1.0</em></strong><em> was </em><a href="https://developers.googleblog.com/a2ui-10-build-delightful-fast-reliable-agentic-experiences/"><em>announced on 11 November</em></a><em> as the first stable version of the protocol. Everything here is still </em><strong><em>v0.9</em></strong><em>, on purpose: the demo pins </em><em>@a2ui/angular 0.13 and </em><em>@a2ui/web_core (written in </em><strong><em>Zod 3</em></strong><em>), and the published packages are still 0.x, behind the final 1.0 spec. On the wire, 1.0 mostly renames: bindings and calls become </em><em>@path and </em><em>@call, and client and server become renderer and agent ( </em><a href="https://github.com/a2ui-project/a2ui/blob/main/specification/v1_0/docs/evolution_guide.md"><em>evolution guide</em></a><em>). The catalog, the validation and the policy below work the same way. Pin your versions.</em></blockquote><h3>🧩 Where the catalog sits</h3><p>A quick map of the demo, because the catalog only makes sense in context (if MCP, A2A, AG-UI and A2UI blur together, <a href="https://lnkd.in/p/dHAyDhPE">this post sorts the four layers</a>):</p><ul><li><strong>Step 1:</strong> The Angular app sends the prompt plus the catalogs it supports, over your own API (POST, SSE reply).</li><li><strong>Step 2:</strong> The app’s server forwards it to the agent over A2A.</li><li><strong>Step 3:</strong> The agent composes the UI from the catalog and validates it: A2UI + your code.</li><li><strong>Step 4:</strong> createSurface / updateComponents messages stream back over A2A, then your SSE.</li><li><strong>Step 5:</strong> &lt;a2ui-v09-surface&gt; renders them with your Angular components, via @a2ui/angular.</li></ul><p>The renderer declares what it can draw with supportedCatalogIds. The agent may only answer with components from those catalogs, so the catalog is the contract between the two sides.</p><h3>🔧 One schema per component</h3><p>Nothing is better than seeing some code in order to understand something. This is the PriorityBadge from the demo&#39;s ticket catalog:</p><pre>export const PRIORITIES = [&#39;low&#39;, &#39;medium&#39;, &#39;high&#39;, &#39;urgent&#39;] as const;<br><br>export const PriorityBadgeApi = {<br>  name: &#39;PriorityBadge&#39;,<br>  schema: z<br>    .object({<br>      priority: z<br>        .union([z.enum(PRIORITIES), DataBindingSchema])<br>        .describe(&quot;The ticket&#39;s priority, or a binding to it.&quot;),<br>    })<br>    .strict()<br>    .describe(&quot;A coloured badge showing a ticket&#39;s priority.&quot;),<br>} satisfies ComponentApi;</pre><p>Three details matter. z.enum limits the value to four strings. DataBindingSchema lets the agent bind the badge to the data model instead of hardcoding a value. And .strict() rejects any prop the schema doesn&#39;t name.</p><p>The components are then assembled with @a2ui/web_core&#39;s own Catalog class, and toJson() produces the JSON Schema document the model reads:</p><pre>export const ticketCatalog = new Catalog&lt;ComponentApi&gt;(<br>  TICKET_CATALOG_ID,<br>  &#39;v0.9&#39;,<br>  [...TICKET_BASIC_COMPONENTS, ...TICKET_CUSTOM_COMPONENTS],<br>  [],<br>  { themeSchema: BasicCatalogThemeSchema, title: &#39;Support ticket catalog&#39; /* … */ },<br>);<br><br>export function ticketCatalogDocument(): Record&lt;string, unknown&gt; {<br>  return ticketCatalog.toJson();<br>}</pre><p>The .describe() strings aren&#39;t decoration: they end up in that document, so they&#39;re the only documentation the model gets.</p><h3>⚛️ The Angular side reads the same object</h3><p>Here is the part I like most as an Angular developer. The component that draws the badge is typed from the very same PriorityBadgeApi:</p><pre>@Component({<br>  selector: &#39;app-priority-badge&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  template: `&lt;span class=&quot;priority-badge&quot; [attr.data-priority]=&quot;priority()&quot;&gt;{{ priority() }}&lt;/span&gt;`,<br>})<br>export class PriorityBadgeComponent extends CatalogComponent&lt;typeof PriorityBadgeApi&gt; {<br>  /** &#39;low&#39; | &#39;medium&#39; | &#39;high&#39; | &#39;urgent&#39;, inferred from the Zod enum. */<br>  protected readonly priority = computed(() =&gt; this.props().priority?.value());<br>}</pre><p>CatalogComponent exposes the props as signals, so the resolved value drops straight into a computed(). Registration pairs each ComponentApi with its component:</p><pre>new AngularCatalog(TICKET_CATALOG_ID, &#39;v0.9&#39;, [<br>  ...BASIC_COMPONENTS.filter((impl) =&gt; basicNames.has(impl.name)),<br>  createComponentImplementation(PriorityBadgeApi, PriorityBadgeComponent),<br>  // …<br>], [], BasicCatalogThemeSchema);</pre><p>Add a fifth priority to the enum and the model’s prompt, the agent’s validation and the component’s types all change together. There is no second list to forget.</p><h3>🔍 What “rejected” looks like</h3><p>The demo has a stub mode ( STUB_LLM=true, no API key) and a flag, STUB_INVALID_FIRST=true, that makes the first answer use a priority outside the enum. This is the agent&#39;s log, verbatim:</p><pre>--- RestaurantExecutor: Attempt 1/2 ---<br>--- A2UI validation failed:<br>    Validation failed for component &#39;PriorityBadge&#39;<br>    (ticket_priority): priority: Invalid enum value.<br>    Expected low | medium | high | urgent,<br>    received &#39;critical&#39; … (Attempt 1) ---<br>--- RestaurantExecutor: Attempt 2/2 ---</pre><p>The agent validates each message against the catalog before publishing it, and on failure retries <strong>once</strong> with the error in the prompt, as the official A2UI restaurant sample does. If both attempts fail, the user gets a text apology instead of a broken surface. A component outside the catalog fails the same way ( Unknown component type &#39;Image&#39; not found in catalog ...), and so does an extra prop ( Unrecognized key(s) in object: &#39;color&#39;).</p><p>One honest caveat: validation runs <strong>per message</strong>, while streaming. If the first message of attempt 1 was valid, it has already reached the browser when a later one fails. Design the retry so it replaces the surface rather than appending to it.</p><h3>💡 The trap: two copies of “the same” schema</h3><p>Here’s the bug that taught me the title of this article (the <a href="https://lnkd.in/p/dQM98WvQ">short version is on LinkedIn</a>). The agent first loaded the basic catalog from its published <strong>JSON</strong> document, while the renderer validated with web_core’s <strong>Zod</strong> objects. They describe the same components, but they’re not equally strict: rebuilt from JSON Schema, a Button action’s context comes back as Record&lt;unknown&gt;.</p><p>So a data binding cut at a chunk boundary streamed out as {}. The agent&#39;s copy accepted it, the renderer&#39;s Zod rejected it, and the form broke in the browser.</p><p>The fix was to register the Zod Catalog object on the agent too. The model still reads toJson() in its prompt, so nothing changed for it, but now both sides validate with the same object. A schema is only as strong as the copy each side holds.</p><h3>🧠 Valid isn’t the same as allowed</h3><p>The catalog answers one question: <em>is this a valid UI?</em> It can’t answer the next one: <em>may this user see it?</em> In the demo, each ticket carries internal_notes for the support team, and the detail view can offer a <em>Delete ticket</em> button. A Text bound to /ticket/internal_notes is a perfectly valid component, and so is a Button whose action is delete_ticket. Validation lets both through.</p><p>So the agent runs a second, deployment-specific check after validation and before anything is published:</p><pre>export const DEMO_POLICY: Policy = {<br>  forbiddenDataPaths: [&#39;/tickets/*/internal_notes&#39;, &#39;/ticket/internal_notes&#39;],<br>  disabledActions: [&#39;delete_ticket&#39;],<br>};</pre><p>applyPolicy is pure and works per message. It deletes forbidden paths from every updateDataModel value, and it removes every component that binds one of them or carries a disabled action, together with its subtree. Then it mends the tree so the surface stays valid against the catalog: a parent drops the id from its children, a Card whose only child is gone goes too, and a template pointing at a removed row becomes an empty list. Removing a component rather than blanking one of its props is deliberate, because a required prop like Text.text can&#39;t simply be emptied.</p><p>The reason it’s per message is streaming. In Direct JSON mode, the agent re-sends a message whole every time it grows, and each re-send goes straight to the browser. In my tests, the raw stream carried internal_notes in re-sends well before the last one, so filtering only the final message would come too late: the filter has to clean every re-send on its own.</p><p>One honest limit: a denylist only covers the shapes you anticipated. My first policy listed /tickets/*/internal_notes and missed the detail view, which binds /ticket/internal_notes. That&#39;s why the deny-by-default version of this, an allowlist of what each view may show, is the one I&#39;d reach for in production.</p><h3>🎯 Swap the transport, keep the catalog</h3><p>A2UI doesn’t care how its messages travel: its roadmap lists A2A, AG-UI, MCP, REST and WebSockets. In the demo the browser never speaks A2A: it POSTs to the app’s own server, and server.ts is the A2A client. It unwraps the A2UI messages from the A2A parts and streams them back as plain SSE, { messages, sessionId }, so the Angular app doesn&#39;t contain a single A2A type.</p><p>That makes the transport a single file. Swap A2A for AG-UI (CopilotKit’s runtime) and steps 1, 2 and 4 change, while the catalog, the validation and the Angular components stay exactly as they are. The architecture does care, though: A2A gives you agent-to-agent delegation that an agent-to-app protocol doesn’t.</p><h3>✅ Closing thoughts</h3><ul><li>Define each component once, as a Zod ComponentApi, and derive everything else from it: the prompt via toJson(), the agent&#39;s validation, the Angular types.</li><li>Make schemas .strict() and enums explicit: anything the catalog doesn&#39;t name is something the agent can&#39;t render.</li><li>Never let the agent and the renderer validate with different copies.</li><li>Validation says what’s <em>valid</em>; a policy after it says what’s <em>allowed</em> for this user, and it has to run on every streamed message.</li></ul><p>Neither the catalog nor a denylist can catch everything, though. A2UI 1.0 narrows the gap a little: a catalog can now declare allowedParents and allowedChildren, so a component in the wrong place gets rejected too. Where the line still sits is one of the things I&#39;ll talk about at <strong>AngularDay on 20 November</strong>. The demo is public and stub mode needs no key: <a href="https://github.com/giorgiogalassi/talk-a2ui/tree/main/demo">github.com/giorgiogalassi/talk-a2ui</a>.</p><p>If you liked it, follow me on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> and <a href="https://medium.com/@giorgio.galassi">Medium</a> for more Angular deep dives.</p><p>See you in the next one! 🤙🏻 <br> — G.</p><p><em>Originally published at </em><a href="https://dev.to/ggalassi/a2ui-in-angular-your-zod-catalog-is-the-trust-boundary-3n89"><em>https://dev.to</em></a><em> on November 16, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922a133328a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular v22.2: Router Resources vs Resolvers — Parallel Data Loading Without the Waterfall ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-v22-2-router-resources-vs-resolvers-parallel-data-loading-without-the-waterfall-1b2d6a4a2b66?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2d6a4a2b66</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[angular-router]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 11:38:30 GMT</pubDate>
            <atom:updated>2026-10-22T11:41:41.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0QoIF7kB64BK4HHQ.png" /></figure><p>Let’s be honest: resolvers were never loved, they were tolerated. You wrote one per piece of data, wired it into resolve, and accepted that a parent route&#39;s resolver had to finish before the child&#39;s could even start. Add two levels of nesting and a slow endpoint, and navigation turns into a waterfall the user watches in real time.</p><p>Angular 22.2 ships an alternative built on the API we’ve been using everywhere else for two years: . Routes can now declare <strong>Router Resources</strong>, and the router loads them for every matched route at the same time.</p><blockquote><em>⚠️ </em><strong><em>Availability:</em></strong><em> Router Resources are </em><em>@developerPreview 22.2. The API can still change before it goes stable, so try it on a feature branch before you migrate a whole app.</em></blockquote><blockquote><em>🧪 </em><strong><em>Try it:</em></strong><em> the </em><a href="https://github.com/giorgiogalassi/angular-article-demos/tree/main/demos/2026-10-01-angular-router-resources"><em>companion demo on GitHub</em></a><em> runs the same routes twice, once with Router Resources and once with resolvers, and logs when every request starts and ends.</em></blockquote><h3>🔧 Turning It On</h3><p>Router Resources are a router feature, opted into next to the ones you probably already have:</p><p>withComponentInputBinding() is optional, but keep it: it powers the nicest part of the API.</p><h3>🧠 Declaring Resources on a Route</h3><p>A route gets a new resources property. It&#39;s a function that receives a context of route signals and returns an object map of resources:</p><p>A few things worth noticing here:</p><ul><li><strong>It runs in an injection context</strong>, so inject() works directly, no factory function needed.</li><li><strong>Any </strong><strong>Resource works:</strong> resource(), <a href="https://dev.to/ggalassi/angular-v19-understanding-the-new-resource-and-rxresource-apis-3393">rxResource()</a>, or your own implementation.</li><li><strong>It can be </strong><strong>async</strong> and return a Promise, handy for a dynamic import() of the API client. One catch: the injection context ends at the first await, so capture inject(Injector) before it and pass it as injector to each resource, or resource() throws NG0203.</li><li><strong>Forward the </strong><strong>abortSignal</strong> to your requests: when the router supersedes or rolls back a navigation, the pending request is aborted instead of finishing for nothing.</li></ul><p>At this point, it’s worth noting a detail from the official guide: read ctx.params()[&#39;id&#39;], not ctx.params(). The router creates a fresh params object on every navigation, so depending on the whole object would reload the resource even when the id didn&#39;t change.</p><blockquote><em>⚠️ </em><strong><em>On 22.2.3 that isn’t enough yet.</em></strong><em> A plain </em><em>params function still reruns the loader on every navigation of the route, even one that only changes a query param or the fragment, with the same id. The cause is in </em><em>resource() itself, and the </em><a href="https://github.com/angular/angular/commit/fe02c34c3c"><em>fix</em></a><em> is merged on the 22.2 branch but not released as of 22.2.3. Until it ships, pass a </em><em>computed() instead of a function: </em><em>const id = computed(() =&gt; ctx.params()[&#39;id&#39;]);, then </em><em>params: id.</em></blockquote><h3>⚡ Blocking vs Non-Blocking</h3><p>This is the real upgrade over resolvers. By default a Router Resource is <strong>blocking</strong>: navigation waits until it resolves, exactly like a resolver did. Wrap it in nonBlocking() and the navigation completes immediately, while the resource keeps loading in the background.</p><p>So the profile above waits for user, because a profile page without a user is meaningless, but it doesn&#39;t hold the user hostage while the activity feed loads.</p><p>And unlike resolvers, which run one route at a time from parent to child, <strong>resources across all matched routes load concurrently</strong>. The waterfall is gone without you having to restructure anything.</p><h3>🎯 Reading the Data in the Component</h3><p>With withComponentInputBinding(), each resource lands on a component input with the same name. The blocking/non-blocking split shows up in the types:</p><p>A blocking resource binds its <strong>value</strong>: by the time the component exists, the data is there. A non-blocking resource binds the <strong>whole </strong><strong>Resource</strong>, because the component has to render the loading and error states itself. Don&#39;t skip the error() branch: reading value() on a resource in the error state throws, which is why the template checks hasValue() before reading it.</p><p>If a key collides, resources win over data (resolvers included), which win over path params, which win over query params.</p><p>Without input binding, the same map is available as ActivatedRoute.resources. The router hands them out read-only: you can read the signals and call reload(), but set() and update() aren&#39;t there.</p><h3>🧪 Try It Yourself</h3><p>The <a href="https://github.com/giorgiogalassi/angular-article-demos/tree/main/demos/2026-10-01-angular-router-resources">demo on GitHub</a> puts both versions of the same routes side by side in <a href="https://github.com/giorgiogalassi/angular-article-demos/blob/main/demos/2026-10-01-angular-router-resources/src/app/app.routes.ts">app.routes.ts</a>. Run it, pick a user under <em>Router Resources</em>, then the same user under <em>Resolvers</em>, and compare the timelines. The checkboxes make the blocking or the non-blocking request fail.</p><pre>git clone https://github.com/giorgiogalassi/angular-article-demos.git <br>cd angular-article-demos/demos/2026-10-01-angular-router-resources <br>npm ci &amp;&amp; npm start</pre><h3>🔁 Reload Without Re-Navigating</h3><p>The second big difference from resolvers: refreshing resolver data meant navigating again, rerunning guards and rematching routes. A Router Resource just reloads:</p><p>reload() returns false while a navigation is in flight or the router is recovering from a cancelled one, so you won&#39;t race the router.</p><p>Or refresh reactively: update any signal the params function reads, and the loader runs again.</p><p>During navigation the router also <strong>freezes</strong> the exposed resources. A reused component keeps showing the previous user until the next one resolves, with no flash of a loading state in between. If the navigation is cancelled, it holds the previous snapshot until the resource settles back.</p><h3>💥 When Loading Fails</h3><p>Errors follow the same split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YxwZLHHxEPlPdS4MfphSA.png" /></figure><p>The last row isn’t in the docs, but the <a href="https://github.com/giorgiogalassi/angular-article-demos/tree/main/demos/2026-10-01-angular-router-resources">companion demo</a> shows it. The docs promise no error state <em>during navigation</em>; a later reload() is outside that promise, and resetting the boundary alone re-renders against a resource that&#39;s still in error.</p><p>The last two cases are where the template has to cope with failure, and Angular 22.2 shipped the right tool for that the same week: . The two features were clearly designed to meet in the middle, and that’s what the companion article covers.</p><h3>✅ Should You Migrate?</h3><p>Not by rewriting every resolver tomorrow: this is developer preview. But the next time you add data to a route, especially one nested under a parent that already resolves something, reach for resources instead of resolve. The rules of thumb:</p><p>Resolvers modelled data loading as a step navigation has to get through. Router Resources model it as state the route owns, which is the same move <a href="https://dev.to/ggalassi/angular-v19-understanding-the-new-httpresource-api-23h">httpResource()</a> made for HTTP calls.</p><p>If you want to go deeper on the resource APIs this is built on, check out my previous articles:</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, signals and modern frontend development.</p><p>I also send the longer, more opinionated version of this kind of thing to a small list — reading the source, and what it changes about how you build. <a href="https://ggalassi.substack.com/">Subscribe here</a>.</p><p>See you in the next one! 🤙🏻<br> — G.</p><p><em>Originally published at </em><a href="https://dev.to/ggalassi/angular-v222-router-resources-vs-resolvers-parallel-data-loading-without-the-waterfall-opj"><em>https://dev.to</em></a><em> on October 22, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2d6a4a2b66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular v22.2: @boundary Ships — $error, $reset() and when in Practice ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-v22-2-boundary-ships-error-reset-and-when-in-practice-bae630de7c69?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae630de7c69</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 12:37:05 GMT</pubDate>
            <atom:updated>2026-10-21T11:58:07.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yyobRwNXvMWKUN00.png" /></figure><p>Back in June, I wrote that <a href="https://medium.com/@giorgio.galassi/angular-v22-boundary-multi-case-switch-and-inline-arrow-functions-9293380f333b">@boundary was coming</a> and that we shouldn&#39;t wait for it in production just yet. Here we are again: it landed in Angular 22.2, and the shipped version does quite a bit more than the one-line teaser we saw at the time.</p><p>Let’s be honest about the problem it solves. One component throws during rendering, and the whole view goes with it. Not the widget, the page. Until now, the only defence was a global ErrorHandler that could log the crash but couldn&#39;t put anything back on screen.</p><blockquote><em>⚠️ </em><strong><em>Availability:</em></strong><em> </em><em>@boundary is in developer preview since Angular 22.2 (it first appeared in </em><em>22.2.0-next.6). Syntax and behaviour can still change before it goes stable.</em></blockquote><blockquote><em>🧪 </em><strong><em>Try it:</em></strong><em> every snippet in this article runs in the </em><a href="https://github.com/giorgiogalassi/angular-article-demos/tree/main/demos/2026-10-01-angular-boundary-in-practice"><em>companion demo on GitHub</em></a><em>, with an on-screen log of where each error ends up.</em></blockquote><pre>@boundary {<br>  &lt;app-revenue-chart /&gt;<br>} @error {<br>  &lt;p&gt;The chart couldn&#39;t load: {{ $error.message }}&lt;/p&gt;<br>  &lt;button (click)=&quot;$reset()&quot;&gt;Try again&lt;/button&gt;<br>}</pre><h3>🛡️ The Basics</h3><p>The shape is the one from June: a @boundary block wraps the risky part of the template, an @error block says what to show instead.</p><p>Two implicit variables are available inside @error:</p><ul><li>is the caught error. Anything thrown that isn’t an Error gets wrapped in an ErrorBoundaryWrappedError, so $error.message is always safe to read.</li><li>is a function. Calling $reset() throws away the fallback and tries to render the primary block again, which is your retry button for free.</li></ul><p>The let syntax from the June teaser still works, as an alias: @error (let err) makes err point to $error. Those two names are the only ones allowed, so there&#39;s no room for typos.</p><h3>🎯 Multiple @error Blocks and when</h3><p>This is the part the teaser didn’t show. You can chain several @error blocks, each with a when condition, and the first one whose condition is truthy wins:</p><pre>@boundary {<br>  &lt;app-chart-dashboard /&gt;<br>} @error (let err; retry = $reset; when isChartError(err)) {<br>  &lt;p&gt;Chart failed: {{ err.message }}&lt;/p&gt;<br>  &lt;button (click)=&quot;retry()&quot;&gt;Retry&lt;/button&gt;<br>} @error {<br>  &lt;p&gt;Something unexpected happened.&lt;/p&gt;<br>}</pre><p>Nothing better than reading the rules straight from the compiler:</p><ul><li><strong>when takes any template expression</strong>, it&#39;s a predicate rather than a type filter. Usually a component method like isChartError(err).</li><li><strong>At most one </strong><strong>@error can be unconditional</strong>, and it has to be the last one in the chain.</li><li><strong>If no block matches</strong>, Angular throws a BoundaryError with the original error as its cause, and that error travels up to the next boundary.</li></ul><blockquote><em>💡 </em><strong><em>Tip:</em></strong><em> the official error-boundaries guide currently pairs an </em><em>isRenderError(err) condition with a &quot;Network issue&quot; message. Don&#39;t copy that example verbatim.</em></blockquote><h3>🧠 What a Boundary Catches, and What It Doesn’t</h3><p>The boundary catches errors thrown while Angular <strong>creates or updates</strong> the views inside it: component constructors, template bindings, lifecycle hooks, @for expressions, effects declared inside the boundary, and lazily or dynamically created components.</p><p>What it doesn’t catch is just as important:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFzWx-x8HwH7zWFXEW_SkA.png" /></figure><p>Nesting follows the same logic. When something throws, Angular walks up the view tree to the closest boundary. If that boundary’s handlers don’t match or throw themselves, it keeps walking.</p><p>When a boundary does catch something, it doesn’t swallow it silently. Angular calls ErrorHandler.onViewError(error, details) if you&#39;ve implemented it, and handleError otherwise. The details object tells you which declaration failed and which boundary caught it, which is exactly what your error tracking wants.</p><blockquote>✏️ <strong><em>Updated Oct 21:</em></strong><em> up to Angular 22.2.1, </em><em>onViewError ran with rendering still tracked, so writing to a signal from it (an on-screen error list, a store) threw </em><em>NG0600and the fallback never rendered. </em><a href="https://github.com/angular/angular/commit/74bc86d8b21c9b48e22adf36923a83c254e00de0"><em>22.2.2 fixed it</em></a><em>: the handler now runs untracked, and a plain signal write works. Still on 22.2.1 or earlier? Defer the write with </em>queueMicrotask()<em>, or upgrade.</em></blockquote><h3>🔁 Where It Gets Interesting: Resources</h3><p>Here’s the detail that makes @boundary click with the rest of modern Angular. Calling value() on a that is in an error state doesn&#39;t return undefined. It <strong>throws</strong>. And a throwing template binding is exactly what a boundary intercepts.</p><p>So you don’t need an @if around error() anymore: let the template read the value and declare the failure path once. You still need one small guard, though, and it&#39;s easy to miss:</p><pre>@boundary {<br>  @if (order.isLoading() &amp;&amp; !order.hasValue()) {<br>    &lt;p&gt;Loading order…&lt;/p&gt;<br>  } @else {<br>    &lt;app-order-summary [order]=&quot;order.value()!&quot; /&gt;<br>  }<br>} @error {<br>  &lt;p&gt;We couldn&#39;t load this order.&lt;/p&gt;<br>  &lt;button (click)=&quot;order.reload(); $reset()&quot;&gt;Retry&lt;/button&gt;<br>}</pre><p>The guard is there because value() throws only in the <strong>error</strong> state. While the resource is loading for the first time, or reloading after an error, it returns undefined, and the child component crashes on that instead. The boundary catches that crash too, so without the guard two things go wrong:</p><ul><li><strong>The first load lands in the fallback</strong>, and it stays there even after the data arrives, because a boundary showing its fallback doesn’t re-render the primary block until $reset().</li><li><strong>order.reload(); $reset() resets too early.</strong> The primary block re-renders while the resource is still reloading, hits undefined, and the fallback comes straight back.</li></ul><p>With the guard, the one-liner retry works: $reset() shows the loading state, then the data. If you&#39;d rather not guard, reload, wait for isLoading() to turn false, and only then call $reset(). The demo has a checkbox that toggles the guard, so you can watch both behaviours.</p><p>This fits the Router Resources that shipped in the same release. A nonBlocking() route resource lets navigation finish even if its loader fails, and the failure surfaces through the resource. Put the part of the page that reads it inside a @boundary, and a failed side panel becomes a contained fallback instead of a broken page.</p><h3>🧪 Try It Yourself</h3><p>The <a href="https://github.com/giorgiogalassi/angular-article-demos/tree/main/demos/2026-10-01-angular-boundary-in-practice">demo on GitHub</a> has every example from this article in one template, in . Run it, toggle the failures, use the retry buttons, and watch the log at the bottom to see which errors reach onViewError and which go to handleError.</p><pre>git clone https://github.com/giorgiogalassi/angular-article-demos.git <br>cd angular-article-demos/demos/2026-10-01-angular-boundary-in-practice <br>npm ci &amp;&amp; npm start</pre><h3>🔧 The Programmatic Version</h3><p>If you render components from code, you get the same mechanism as an onError option on ViewContainerRef.createComponent, createEmbeddedView and createComponent. One difference: unlike @boundary, it doesn&#39;t catch errors thrown in the component&#39;s constructor.</p><h3>✅ How I’d Start Using It</h3><p>Developer preview means “try it”, not “wrap everything”. A few sensible first steps:</p><ul><li><strong>Wrap the widgets you don’t control</strong>: third-party embeds, user-generated content, feature-flagged experiments.</li><li><strong>Pair it with resources</strong> where a missing piece of data shouldn’t take down the page, with an isLoading() &amp;&amp; !hasValue() guard inside.</li><li><strong>Implement </strong><strong>onViewError</strong> so caught errors still reach your monitoring. On 22.2.2 or later, writing to a signal from it is fine.</li><li><strong>Keep event-handler errors in mind</strong>, because they’re the ones a boundary will never see.</li></ul><p>In June, @boundary was a promise of &quot;crash isolation&quot; in the template. In 22.2 it&#39;s a full error-handling model, with conditions, retries and a clean hand-off to your ErrorHandler. The template layer keeps getting more resilient, one block at a time.</p><p>If you want to go deeper on the template features that got us here, check out my previous articles:</p><ul><li><a href="https://medium.com/@giorgio.galassi/angular-v22-boundary-multi-case-switch-and-inline-arrow-functions-9293380f333b">Angular v22 — </a><a href="https://medium.com/@giorgio.galassi/angular-v22-boundary-multi-case-switch-and-inline-arrow-functions-9293380f333b">@boundary, Multi-Case Switch, and Inline Arrow Functions</a></li><li><a href="https://dev.to/ggalassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-1m56">Understanding </a><a href="https://dev.to/ggalassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-1m56">@defer — Part 1 (v18+)</a></li><li><a href="https://dev.to/ggalassi/angular-v19-understanding-the-new-resource-and-rxresource-apis-3393">Angular v19+ — Understanding the New </a><a href="https://dev.to/ggalassi/angular-v19-understanding-the-new-resource-and-rxresource-apis-3393">resource() and </a><a href="https://dev.to/ggalassi/angular-v19-understanding-the-new-resource-and-rxresource-apis-3393">rxResource() APIs</a></li></ul><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, signals and modern frontend development.</p><p>I also send the longer, more opinionated version of this kind of thing to a small list — reading the source, and what it changes about how you build. <a href="https://ggalassi.substack.com/">Subscribe here</a>.</p><p>See you in the next one! 🤙🏻<br> — G.</p><p><em>Originally published at </em><a href="https://dev.to/ggalassi/angular-v222-boundary-ships-error-reset-and-when-in-practice-3db"><em>https://dev.to</em></a><em> on October 5, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae630de7c69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[validateHttp() Has No Async Machinery: A Trace From Signal Forms Down to fetch() ]]></title>
            <link>https://medium.com/@giorgio.galassi/validatehttp-has-no-async-machinery-a-trace-from-signal-forms-down-to-fetch-aef0250c9c2c?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef0250c9c2c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 09:46:25 GMT</pubDate>
            <atom:updated>2026-08-30T07:01:02.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvCcnJQAGl2FKZBn.png" /></figure><p>Let’s be honest: async validation is the part of any forms library where you brace yourself. Debouncing, cancelling the request the user just invalidated by typing another character, keeping a “checking…” spinner honest, not letting a slow response overwrite a fast one. Every library that has ever done this has grown a pile of bespoke machinery for it.</p><p>So when <a href="https://angular.dev/guide/forms/signals/overview">Signal Forms</a> shipped <a href="https://angular.dev/api/forms/signals/validateHttp">validateHttp()</a> and it just worked, I wanted to see the pile. I opened the source expecting a few hundred lines of async bookkeeping, and instead found a function whose entire body is a single call to something else.</p><p>That turned into a trace all the way down, from a form field to the line where bytes actually leave the browser. Six layers, and only two of them add anything you could call new async machinery.</p><blockquote><em>✅ </em><strong><em>Availability:</em></strong><em> </em><em>validateHttp() is </em><em>@publicApi 22.0, stable. Every source reference in this article is pinned to the </em><a href="https://github.com/angular/angular/tree/v22.1.1"><em>v22.1.1 tag</em></a><em>, so the line numbers stay valid even as </em><em>main moves.</em></blockquote><h3>🧩 The View From Outside</h3><p>The usage is unremarkable, which is the point. You declare that a field validates against an endpoint, and you’re done:</p><pre>const schema = form(this.model, (path) =&gt; {<br>  validateHttp(path.username, {<br>    request: ({ value }) =&gt; `/api/username-available?u=${value()}`,<br>    debounce: 300,<br>    onError: () =&gt; ({ kind: &#39;server-unreachable&#39; }),<br>    onSuccess: (res: { available: boolean }) =&gt;<br>      res.available ? undefined : { kind: &#39;username-taken&#39; },<br>  });<br>});</pre><p>Sync validators run first, the request waits until they pass, field().pending() is true while it&#39;s in flight, and typing again cancels the previous call. If you&#39;ve read <a href="https://medium.com/@giorgio.galassi/angular-forms-validation-and-form-state-part-3-0f2db5b4961e">Part 3 of my Signal Forms series</a>, that&#39;s the behaviour contract you already know. The question here is who implements it.</p><h3>🔍 Layer 1: validateHttp() Is a Delegation</h3><p>Here is the whole function, from <a href="https://github.com/angular/angular/blob/v22.1.1/packages/forms/signals/src/api/rules/validation/validate_http.ts#L96-L110">validate_http.ts</a>:</p><pre>export function validateHttp(path, opts) {<br>  validateAsync(path, {<br>    params: opts.request,<br>    debounce: opts.debounce,<br>    factory: (request) =&gt; httpResource(request, opts.options),<br>    onSuccess: opts.onSuccess,<br>    onError: opts.onError,<br>    when: opts.when,<br>  });<br>}</pre><p>That’s it. No await, no subscription, no cancellation logic. The URL function you wrote becomes the params of something, and <a href="https://medium.com/@giorgio.galassi/angular-v19-understanding-the-new-httpresource-api-837e1dadc990">httpResource()</a> gets handed over as a factory. Out of the whole file, that factory is the only line that does anything HTTP-related; everything else naming HTTP is an import, a type or a doc comment.</p><p>So the async machinery is in validateAsync. Let&#39;s go there.</p><h3>🧠 Layer 2: Three Behaviours, Zero New Mechanisms</h3><p><a href="https://github.com/angular/angular/blob/v22.1.1/packages/forms/signals/src/api/rules/validation/validate_async.ts#L128-L180">validate_async.ts</a> is where I expected the pile to be. It isn&#39;t there either. Three behaviours, each one built from something that already existed.</p><p><strong>Sync-before-async gating is just returning </strong><strong>undefined.</strong> The computation that feeds the resource&#39;s params does this:</p><pre>if (validationState.shouldSkipValidation() || !validationState.syncValid()) {<br>  return undefined;<br>}</pre><p>A <a href="https://angular.dev/guide/signals/resource">resource()</a> whose params computation returns undefined sits in idle and never calls its loader — loadEffect() returns early as soon as it sees extRequest.request === undefined. That&#39;s documented public behaviour, not a forms detail. The docs promise that async validation runs only after all synchronous validation passes. Nobody implemented that promise here. It falls out of a rule that was already there.</p><p><strong>pending() is a resource status, read through a validator.</strong> The async error rule is a switch (lightly condensed here — the real one wraps each result in addDefaultField() to attach it to the field):</p><pre>switch (res.status()) {<br>  case &#39;idle&#39;:                      return undefined;<br>  case &#39;loading&#39;: case &#39;reloading&#39;: return &#39;pending&#39;;<br>  case &#39;resolved&#39;: case &#39;local&#39;:<br>    return res.hasValue() ? opts.onSuccess(res.value()!, ctx) : undefined;<br>  case &#39;error&#39;:                     return opts.onError(res.error(), ctx);<br>}</pre><p>Six resource statuses collapse into four form outcomes. field().pending() holds no state of its own, it&#39;s a projection of res.status().</p><p><strong>Debounce composes two existing primitives instead of writing a timer:</strong></p><pre>if (opts.debounce !== undefined) {<br>  const debouncedResource = debounced(() =&gt; params(), opts.debounce);<br>  const wrappedParams = computed(() =&gt; ɵchain(debouncedResource));<br>  return opts.factory(wrappedParams);<br>}</pre><p><a href="https://angular.dev/guide/signals/debounced">debounced()</a> is a public (still experimental) @angular/core primitive, and ɵchain is the internal side of ctx.chain(), the resource-composition helper you reach through a params context. The file does declare export function chain(), but it carries no @publicApi marker and is not surfaced on @angular/core&#39;s public entry point, which is why the forms code reaches it through the ɵ-prefixed alias rather than importing it by name. The forms team is chaining a debounced resource into a loader&#39;s params exactly the way you would chain any two resources in your own code. Worth noticing that they&#39;re dogfooding an experimental API in a stable feature.</p><h3>⚙️ Layer 3: httpResource() Swaps the Loader</h3><p><a href="https://github.com/angular/angular/blob/v22.1.1/packages/common/http/src/resource.ts#L336-L463">httpResource()</a> extends ResourceImpl and doesn&#39;t override any of the loading logic. It passes in a loader that subscribes to HttpClient, and it adds three signals. progress and statusCode are linkedSignals sourced from the request, so changing the request resets them with no reset code involved. headers is a computed on top of one, and it stays undefined until the status is resolved or error, so you never read half-filled headers mid-flight.</p><p>The one place a reset <em>is</em> written by hand is override set(), which clears all three when you write a value locally. The signal graph covers the request path; the local-write path doesn&#39;t go through it.</p><p>One line inside that loader is the bridge between the signal world and the HTTP world:</p><pre>sub = this.client.request(request!).subscribe({ /* ... */ });</pre><h3>🔧 Layer 4: The Pipeline Everything Shares</h3><p><a href="https://github.com/angular/angular/blob/v22.1.1/packages/core/src/resource/resource.ts#L203-L345">ResourceImpl</a> is the actual engine, and it&#39;s four reactive nodes. The one I&#39;d single out is the state machine, because it explains a UI behaviour you&#39;ve probably relied on without asking why:</p><pre>// the branch taken when the resource already has previous state<br>status = request === undefined ? &#39;idle&#39; : &#39;loading&#39;;</pre><p>There are two of these, one per branch of an if/else inside that linkedSignal. The first covers initialisation and can also resolve straight from an initial stream; the second is the one above, taken when params change on a resource that already exists. Both send undefined to &#39;idle&#39;. That expression runs inside a linkedSignal, which means it&#39;s <strong>not behind an await</strong>. linkedSignal is lazy, it recomputes on read rather than on write, but that recomputation is pure and synchronous: the first read of status() after your params change already returns &#39;loading&#39;, and pending() is already true, in the same tick, before any promise exists. Only the data is async. If you&#39;ve ever wondered why Signal Forms&#39; pending state doesn&#39;t flicker, that&#39;s the reason: the state transition doesn&#39;t live inside the async function.</p><p>The loader itself is called by exactly one <a href="https://github.com/angular/angular/blob/v22.1.1/packages/core/src/resource/resource.ts#L411-L516">effect</a> whose only tracked dependency is the request. Nobody calls the loader imperatively. The graph decides that work should happen, and a single effect does it. It&#39;s the same lazy, pull-based model I traced in <a href="https://medium.com/@giorgio.galassi/angular-internals-1-linkedsignal-writes-back-a-trace-through-the-reactive-graph-e9f09cef4705">Internals #1</a>, which is a good sign: you learn this machine once and it keeps showing up.</p><h3>🔌 Layer 5: Where the Trace Goes Dark</h3><p>Follow client.request(...) downward and you hit a wall. <a href="https://angular.dev/guide/http">HttpClient</a> hands off to HttpHandler, HttpHandler hands off to HttpBackend, and both of those are abstract classes with a single handle() method and no implementation. Grep as hard as you like, no import leads to the code that touches the network.</p><p>That’s because the binding isn’t an import, it’s a provider. From <a href="https://github.com/angular/angular/blob/v22.1.1/packages/common/http/src/provider.ts#L122-L141">provider.ts</a>, reformatted here to fit the width (the real HttpBackend entry uses a block-bodied factory, and each object sits on its own lines):</p><pre>const providers: Provider[] = [<br>  HttpClient,<br>  FetchBackend,<br>  HttpInterceptorHandler,<br>  {provide: HttpHandler, useExisting: HttpInterceptorHandler},<br>  {provide: HttpBackend, useFactory: () =&gt; inject(FetchBackend)},<br>  {provide: HTTP_INTERCEPTOR_FNS, useValue: xsrfInterceptorFn, multi: true},<br>];</pre><p>provideHttpClient() is the only place in the framework where those two abstract tokens get a concrete answer. Two details are easy to get wrong here. First, HttpClient itself is @Injectable({providedIn: &#39;root&#39;}) and FetchBackend is auto-provided too, so both classes are reachable from a bare injector. Forgetting provideHttpClient() doesn&#39;t fail on HttpClient, it fails with No provider for HttpHandler, because the class resolves and its dependency doesn&#39;t. Second, re-listing HttpClient and the backends in that array isn&#39;t redundant. It re-provides them at the environment injector where you called the function. That&#39;s what lets a lazy route have its own interceptors, instead of everything collapsing onto one root instance.</p><p>This is also why swapping the transport is a one-line change. withXhr() pushes {provide: HttpBackend, useExisting: HttpXhrBackend} on top, and withFetch() does the same with FetchBackend, which is why it&#39;s now deprecated: fetch is already the default.</p><h3>🌐 Layer 6: The Floor</h3><p><a href="https://github.com/angular/angular/blob/v22.1.1/packages/common/http/src/fetch.ts#L78-L146">FetchBackend</a> is where Angular stops and the platform starts:</p><pre>private readonly fetchImpl =<br>  inject(FetchFactory, {optional: true})?.fetch ?? ((...args) =&gt; globalThis.fetch(...args));<br><br>const fetchPromise = this.ngZone.runOutsideAngular(() =&gt;<br>  this.fetchImpl(request.urlWithParams, {signal, ...init}),<br>);</pre><p>Even the last hop is injectable. And notice handle() returns new Observable(...), so nothing was sent until layer 3 called .subscribe(). The cold Observable is the hinge the whole chain turns on: the resource&#39;s effect decides when, and the subscription is the trigger.</p><p>Cancellation runs back up the same path in reverse. Typing another character changes the params signal, so the effect aborts its AbortController, the httpResource loader unsubscribes, the RxJS teardown aborts a <strong>second</strong> AbortController inside FetchBackend, and that one is the signal handed to fetch. Four different cancellation idioms relayed in sequence, with a staleness check at the top that rejects a late response by object identity in case anything slips through.</p><h3>✅ Closing Thoughts</h3><p>Lined up, the whole stack is one pipeline with one part swapped at each level:</p><ul><li><strong>validateHttp()</strong> swaps the params. It adds nothing at all, the body is one delegating call.</li><li><strong>validateAsync()</strong> swaps the params again, now gated and debounced, and adds the translation from resource status into form errors.</li><li><strong>httpResource()</strong> swaps the loader, and adds headers(), statusCode() and progress().</li><li><strong>ResourceImpl</strong> swaps nothing, because it <em>is</em> the pipeline. Status, cancellation and staleness live here.</li><li><strong>HttpClient</strong> swaps the transport through DI, and adds interceptors, XSRF and the transfer cache.</li><li><strong>FetchBackend</strong> swaps nothing either, because it&#39;s the floor. It still does real work down there — chunked body reading, download progress, timeouts — but none of it is the async machinery we came looking for. Underneath it all is globalThis.fetch.</li></ul><p>The reason this matters beyond trivia: there’s no forms-specific async system to learn, work around, or wait on the team to extend. If you understand <a href="https://medium.com/@giorgio.galassi/angular-v19-understanding-the-new-resource-and-rxresource-apis-8a387c7d9351">resource()</a>, you already understand validateHttp(), and anything it does you can reproduce with public APIs. Gate a loader by returning undefined. Render pending state off status(). Debounce by chaining a debounced() resource into your params. That&#39;s the entire feature.</p><p>It’s also a fair signal about the abstraction’s honesty. A thin layer over primitives you can reach yourself is one you can debug at 6pm on a Friday, and one that inherits every improvement made underneath it for free.</p><p>If you want to walk it yourself, clone the repo at v22.1.1 and read in this order: validate_http.ts, validate_async.ts, common/http/src/resource.ts, then core/src/resource/resource.ts (the constructor, then loadEffect). A nice runtime check: provide a custom FetchFactory that logs, then type into a validateHttp field and watch one line appear at the bottom of a five-layer stack.</p><p>For the usage side of Signal Forms, <a href="https://medium.com/@giorgio.galassi/angular-forms-model-setup-and-ui-binding-part-1-8143b8b58fdf">Part 1</a> through <a href="https://medium.com/@giorgio.galassi/angular-forms-advanced-patterns-part-4-1de423db0671">Part 4</a> of the series cover the API from the outside. This one was the floor beneath it.</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, web performance, and modern frontend development.</p><p>I also send the longer, more opinionated version of this kind of thing to a small list — reading the source, and what it changes about how you build. <a href="https://ggalassi.substack.com/">Subscribe here</a>.</p><p>See you in the next one! 🤙🏻 <br>— G.</p><p><em>Originally published at </em><a href="https://dev.to/ggalassi/validatehttp-has-no-async-machinery-a-trace-from-signal-forms-down-to-fetch-54n6"><em>https://dev.to</em></a><em> on August 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef0250c9c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[linkedSignal() Writes Back: A Trace Through the Reactive Graph ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-internals-1-linkedsignal-writes-back-a-trace-through-the-reactive-graph-e9f09cef4705?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f09cef4705</guid>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 17:25:38 GMT</pubDate>
            <atom:updated>2026-08-18T12:18:49.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C1zuzzA01P0QyPE5" /><figcaption>Photo by <a href="https://unsplash.com/@heftiba?utm_source=medium&amp;utm_medium=referral">Toa Heftiba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s be honest: <a href="https://angular.dev/guide/signals/linked-signal">linkedSignal()</a> always had a bit of a split personality. It read beautifully from another signal, deriving a value that stayed in sync automatically. But the moment you needed to write back to that source, you were on your own, writing a separate method, converting the value by hand, and hoping you didn&#39;t forget to call it from every place that touched the field.</p><p>Angular 22.1 closes that gap. linkedSignal() can now take a custom set() option, and the linkedSignal becomes a genuine two-way field: read from a larger piece of state, write back to it, no disconnected duplicate copy of the data anywhere.</p><p>My first reaction when I saw this: if the linkedSignal reads a source signal, and writing to the linkedSignal updates that same source, doesn’t that loop forever? It didn’t feel obvious to me, so I went and traced through the actual reactive graph source to settle it, and that turned into a nice little tour of how Angular’s signals actually work.</p><blockquote><em>✅ </em><strong><em>Availability:</em></strong><em> the custom </em><em>set() option shipped in Angular 22.1.0 (stable) and is documented in the official </em><a href="https://angular.dev/guide/signals/linked-signal#customizing-the-set-operation"><em>linkedSignal guide</em></a><em>.</em></blockquote><h3>🧩 Before: Reading Was Clean, Writing Wasn’t</h3><p>Here’s the classic shape. A profile signal holds the real state, and a linkedSignal exposes one field of it:</p><pre>protected readonly profile = signal&lt;UserProfile&gt;({<br>  id: 1,<br>  name: &#39;Brian&#39;,<br>  email: &#39;brian@example.com&#39;,<br>  maxMarketingEmailsPerWeek: 2,<br>});<br><br>protected readonly maxMarketingEmailsPerWeek = linkedSignal(<br>  () =&gt; this.profile().maxMarketingEmailsPerWeek<br>);</pre><p>Reading maxMarketingEmailsPerWeek() is effortless. Writing back to profile is not: you need a second method that does the profile.update() dance, and every button, every input handler, has to remember to call that method instead of the linkedSignal directly. The read side and the write side live in two different places for what is conceptually one piece of state.</p><h3>🔧 After: A Custom set()</h3><p>The fix is a set function passed alongside the computation:</p><pre>protected readonly maxMarketingEmailsPerWeek = linkedSignal(<br>  () =&gt; this.profile().maxMarketingEmailsPerWeek,<br>  {<br>    set: (value) =&gt; {<br>      this.profile.update((profile) =&gt; ({<br>        ...profile,<br>        maxMarketingEmailsPerWeek: value,<br>      }));<br>    },<br>  }<br>);</pre><p>Now maxMarketingEmailsPerWeek.set(5) and .update(v =&gt; v + 1) both flow through that setter and land on profile. The helper method is gone. The simplest version of this idea, straight from the <a href="https://angular.dev/guide/signals/linked-signal#customizing-the-set-operation">Angular docs</a>, is a temperature converter:</p><pre>const tempC = signal(0);<br>const tempF = linkedSignal(() =&gt; (tempC() * 9) / 5 + 32, {<br>  set: (valF) =&gt; tempC.set(((valF - 32) * 5) / 9),<br>});<br><br>tempF.set(212);<br>console.log(tempC()); // 100<br>console.log(tempF()); // 212</pre><h3>🧠 Wait, Doesn’t This Loop?</h3><p>Here’s where I got stuck. tempF reads tempC() inside its computation, so tempF is a genuine dependent of tempC in the reactive graph. When tempC.set(100) runs inside the custom setter, that dependency absolutely gets marked dirty and tempF absolutely does recompute. If it didn&#39;t, tempF() would show a stale value after the conversion, and the whole feature would be pointless.</p><p>So the question I actually needed answered was: does that recompute call the custom setter again? It doesn’t, and the reason is architectural, not incidental.</p><h3>🔍 Under the Hood: The Write Path</h3><p>linkedSignal&#39;s public write API, defined in <a href="https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/linked_signal.ts">linked_signal.ts</a>, looks like this once a custom setter is supplied:</p><pre>const rawSet = (newValue: D) =&gt; linkedSignalSetFn(node, newValue);<br>upgradedGetter.set = (newValue: D) =&gt; customSet(newValue, rawSet);<br>upgradedGetter.update = (updateFn: (value: D) =&gt; D) =&gt;<br>  customSet(updateFn(untracked(getter)), rawSet);</pre><p>Calling tempF.set(212) invokes exactly one thing: your customSet function. It never touches tempF&#39;s own internal value directly, unless your function explicitly calls the rawSet escape hatch it&#39;s handed. In the temperature example, it doesn&#39;t, it only calls tempC.set(100).</p><p>The temperature example never reaches for that second parameter, but there are two situations where you would. One is performance: when computation is expensive and you already know the exact result, rerunning it is wasted work. The other is less obvious: not every linkedSignal has an invertible relationship with its source the way tempF/tempC do. Plenty of real computation functions, summarizing, rounding, picking one field out of several possible source states, can&#39;t be inverted into a single correct value to write back. rawSet covers both: it&#39;s a direct line to the exact primitive that backs the default .set() when there&#39;s no custom setter at all, letting you plant the value directly instead of inverting through the source:</p><pre>} else {<br>  upgradedGetter.set = (newValue: D) =&gt; linkedSignalSetFn(node, newValue);<br>  upgradedGetter.update = (updateFn) =&gt; linkedSignalUpdateFn(node, updateFn);<br>}</pre><p>rawSet is (newValue) =&gt; linkedSignalSetFn(node, newValue), the same call, just handed to you as an argument instead of wired up automatically. Here&#39;s what that function actually does, from the <a href="https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/linked_signal.ts">signal primitives</a>:</p><pre>export function linkedSignalSetFn&lt;S, D&gt;(node: LinkedSignalNode&lt;S, D&gt;, newValue: D) {<br>  producerUpdateValueVersion(node); // resolve any pending staleness first<br>  signalSetFn(node, newValue);      // plain field write: node.value = newValue, version++<br>  producerMarkClean(node);          // mark the node up to date<br>}</pre><p>Three steps: settle any recompute that’s already overdue, write node.value directly with the same primitive a plain signal() uses (never touching node.computation or node.sourceValue), then mark the node clean.</p><p>That first step is worth pausing on, because “settle any overdue recompute” is literal. If the linkedSignal is currently dirty, its source changed since anyone last read it, producerUpdateValueVersion runs producerRecomputeValue before your value ever gets written, which means computation fires once, and if it has any observable side effects, they happen. Your value always wins in the end, the freshly recomputed result gets overwritten immediately after, but &quot;computation never runs&quot; isn&#39;t quite true in that specific case. The mark-clean step is what matters for everything <em>after</em> this call: it tells the next read&#39;s staleness check that the node is current, so from then on producerRecomputeValue is skipped, regardless of what the source is doing in the meantime.</p><p>Line them up and there are three distinct write paths, not two:</p><ul><li><strong>Default </strong><strong>.set(), no custom setter.</strong> Calls linkedSignalSetFn(node, v) directly. computation doesn&#39;t run because of this call, though it does run once first if the node was already stale from an earlier, unread source change.</li><li><strong>Custom </strong><strong>.set(), setter writes to the source</strong> (the temperature example). Only the source&#39;s own version bumps; this node is marked dirty but otherwise untouched. computation re-runs lazily, the next time something reads the linkedSignal.</li><li><strong>Custom </strong><strong>.set(), setter calls </strong><strong>rawSet(v).</strong> Identical to the first case, linkedSignalSetFn(node, v), same caveat about a pending stale recompute settling first.</li></ul><p>Here’s the performance case: a custom setter with independent knowledge of the right answer, where redoing the computation would be wasted work:</p><pre>const items = signal&lt;Item[]&gt;(hugeInitialList);<br><br>const sortedItems = linkedSignal(<br>  () =&gt; expensiveSort(items()), // recomputes whenever items() changes<br>  {<br>    set: (value, rawSet) =&gt; {<br>      // We just got an already-sorted page back from the server -<br>      // no need to re-run expensiveSort() for a value we already know.<br>      rawSet(value);<br>    },<br>  },<br>);<br><br>sortedItems.set(pageFromServer); // writes directly, skipping a fresh expensiveSort() run</pre><p>Compare that to the temperature example: there, the setter calls tempC.set(...) because it genuinely needs tempF to re-derive from the new tempC. Here, the setter already has the final value, so it bypasses the derivation instead of inverting it.</p><p>And here’s the other case, where inverting through the source isn’t just wasteful, it doesn’t make sense at all:</p><pre>const rawInput = signal(&#39;42.7&#39;);<br><br>const roundedValue = linkedSignal(<br>  () =&gt; Math.round(Number(rawInput())),<br>  {<br>    set: (value, rawSet) =&gt; {<br>      // Multiple rawInput strings round to the same integer, there&#39;s<br>      // no single correct string to write back, so just store the value.<br>      rawSet(value);<br>    },<br>  },<br>);</pre><p>Rounding is lossy: many different rawInput values produce the same roundedValue, so there&#39;s no correct string for the setter to write back to rawInput. rawSet sidesteps the question entirely, it&#39;s the same direct write the default .set() would give you if there were no custom setter at all.</p><p>Both cases share the same shape: rawSet is for when inverting through the source is either wasteful or doesn&#39;t make sense, and you&#39;d rather just set the value. It also keeps a single public method for callers: .set(x) works the same way from the outside whether this particular value is a normal edit that should flow through the source, or a precomputed result the setter recognizes and stores directly. The linkedSignal, not the caller, decides which applies.</p><p>That’s the entire write path, everything .set() and .update() can reach, custom setter or not. rawSet can reach into the recompute machinery to settle a pending stale value, but never the other way around.</p><h3>⚙️ Under the Hood: The Recompute Path</h3><p>The recompute lives somewhere else entirely, in the <a href="https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/linked_signal.ts">signal primitives</a>:</p><pre>const linkedSignalGetter = () =&gt; {<br>  producerUpdateValueVersion(node); // check staleness, recompute if needed<br>  producerAccessed(node);<br>  return node.value;<br>};</pre><p>Every signal getter, plain <a href="https://angular.dev/guide/signals">signal()</a>, <a href="https://angular.dev/guide/signals#computed-signals">computed()</a>, or linkedSignal(), is shaped this way. <a href="https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/graph.ts">producerUpdateValueVersion</a> checks whether any dependency&#39;s version changed since the last read, and if so, calls <a href="https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/linked_signal.ts">producerRecomputeValue</a>, which reruns the computation and assigns straight to node.value as a plain field write:</p><pre>newValue = node.computation(newSourceValue, prev);<br>node.sourceValue = newSourceValue;<br>// ...<br>node.value = newValue;<br>node.version++;</pre><p>That’s the whole answer. tempC.set(100) only flips a dirty flag and bumps a version counter, no computation runs at that moment. The actual recomputation is deferred until the next time something reads tempF(), and when it happens, it happens through producerRecomputeValue, a function that has never heard of customSet. Not directly, not indirectly. There&#39;s no code path in the primitives package that leads back to your setter. That direction is the one that would actually matter: if recomputation could call back into customSet, that&#39;s the loop you&#39;d have to worry about, and it provably can&#39;t. The reverse isn&#39;t quite as absolute, rawSet can call into producerRecomputeValue to settle a pending stale value, as covered above, but even then it only ever reaches this same recompute logic, never back into your setter. That asymmetry, not a strict mutual isolation, is the whole reason a linkedSignal can safely both read from and write to the same piece of state.</p><p>One detail worth keeping in mind: this recompute isn’t scheduled for later, it’s synchronous and pull-based. If tempF() is read inside another computed(), the staleness check and recompute for tempF happen inline, in the same call stack, before that outer computed can finish. Angular&#39;s signals are lazy all the way down: nothing recalculates until someone actually asks for a value, but once something does ask, the whole stale chain resolves immediately, in dependency order.</p><h3>✅ Closing Thoughts</h3><p>So, back to the question that opened this piece: no, it doesn’t loop, and now you know exactly why: producerRecomputeValue can&#39;t reach back into customSet, only rawSet reaches the other way. That one-way gap is what makes it safe.</p><p>The custom set() option is a small addition on paper, one new field in an options object, but it changes what linkedSignal() is for. Before, it was a read-only derivation with a writable escape hatch bolted on by convention (the default set/update, with no custom setter, just overwrites the linkedSignal&#39;s own value directly). Now it can be the field-level API for a slice of larger state, without ever creating a second source of truth. And it does that safely because Angular&#39;s signal graph keeps &quot;someone wrote to me&quot; and &quot;one of my dependencies changed&quot; as two structurally separate events, not because of anything defensive in the code you write.</p><p>If you haven’t read <a href="https://medium.com/@giorgio.galassi/angular-v19-computed-vs-linkedsignal-signals-3130b70861b8">my earlier piece comparing </a><a href="https://medium.com/@giorgio.galassi/angular-v19-computed-vs-linkedsignal-signals-3130b70861b8">computed() and </a><a href="https://medium.com/@giorgio.galassi/angular-v19-computed-vs-linkedsignal-signals-3130b70861b8">linkedSignal()</a>, that&#39;s the conceptual &quot;when to reach for which&quot; companion to this one, this article is the deep end: the internals that explain why the two-way version is safe.</p><p>If you’re touching linkedSignal() in a codebase that also uses <a href="https://angular.dev/guide/forms/signals/overview">Signal Forms</a> or <a href="https://angular.dev/guide/signals/resource">resource()</a>, the same lazy, pull-based recompute model is running underneath all of them. Worth understanding once, pays off everywhere.</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, web performance, and modern frontend development.</p><p>See you in the next one! 🤙🏻 <br>— G.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f09cef4705" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Forms — Advanced Patterns (Part 4) ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-forms-advanced-patterns-part-4-1de423db0671?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/1de423db0671</guid>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[signal-forms]]></category>
            <category><![CDATA[sofware-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 07:31:00 GMT</pubDate>
            <atom:updated>2026-11-05T10:58:22.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*plDaL34GN5LzgJAm" /><figcaption>Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_source=medium&amp;utm_medium=referral">Xavi Cabrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Parts 1–3, we built the foundation: model setup, data flow, and validation across Template-driven, Reactive, and Signal Forms. In this final part, we tackle the patterns that show up in production.</p><p>📚 This article is Part 4 of a series on Angular Forms. Start from Part 1 to understand where the form model lives and how it binds to the UI.</p><blockquote><a href="https://medium.com/@giorgio.galassi/angular-forms-model-setup-and-ui-binding-part-1-8143b8b58fdf"><em>Angular Forms — Model Setup and UI Binding (Part 1) 🔥🚀</em></a></blockquote><p>🧪 All examples in this article are available in an interactive StackBlitz playground, where you can explore dynamic fields, async validation, and custom controls hands-on.</p><blockquote><em>⚡ </em><a href="https://stackblitz.com/~/github.com/giorgiogalassi/angular-forms-validation-and-form-state-p4"><em>StackBlitz project — Part 4</em></a></blockquote><p>Signal Forms are stable in Angular v22. That changes things. For the first time in this series, the experimental warning comes off.</p><p>This is the article where the full picture clicks into place.</p><p>To keep things realistic, we graduate from the simple login form we used in Parts 1–3. This part introduces a registration form — a more natural domain for dynamic fields, async validation, and custom controls.</p><h3>⚡ A Quick Note on Angular v22</h3><p>Starting from v22, Signal Forms ship as a stable API. The @angular/forms/signals package is no longer experimental. You can use it in production without bracing for breaking changes.</p><p>If you have existing articles or codebases carrying the experimental disclaimer, now is the time to update them.</p><blockquote><em>💡 </em><strong><em>Signal Forms are not a drop-in replacement for Reactive or Template-driven Forms.</em></strong><em> They are a rethought-from-scratch implementation. The core concepts — validation state, touched, dirty, pending — remain familiar. The API is different by design.</em></blockquote><h3>🧱 Baseline: The Registration Form</h3><p>Throughout this article we use the same domain: a registration form with a username, an email, a password, and a dynamic list of phone numbers. The model stays consistent across sections so the differences between approaches stay the focus.</p><p>Here is the minimal setup for each, without validation or dynamic fields yet — those come in the next sections.</p><p><strong>Template-driven</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormsModule, NgForm } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  imports: [FormsModule],<br>  template: `<br>    &lt;form #f=&quot;ngForm&quot; (ngSubmit)=&quot;submit(f)&quot;&gt;<br>      &lt;input name=&quot;username&quot; [(ngModel)]=&quot;model.username&quot; /&gt;<br>      &lt;input name=&quot;email&quot;    [(ngModel)]=&quot;model.email&quot; /&gt;<br>      &lt;input name=&quot;password&quot; type=&quot;password&quot; [(ngModel)]=&quot;model.password&quot; /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Register&lt;/button&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class RegistrationComponent {<br>  model = { username: &#39;&#39;, email: &#39;&#39;, password: &#39;&#39; };<br><br>  submit(form: NgForm): void {<br>    console.log(form.value);<br>  }<br>}</pre><p><strong>Reactive</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormGroup, FormControl, Validators, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  imports: [ReactiveFormsModule],<br>  template: `<br>    &lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;submit()&quot;&gt;<br>      &lt;input formControlName=&quot;username&quot; /&gt;<br>      &lt;input formControlName=&quot;email&quot; /&gt;<br>      &lt;input formControlName=&quot;password&quot; type=&quot;password&quot; /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Register&lt;/button&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class RegistrationComponent {<br>  form = new FormGroup({<br>    username: new FormControl(&#39;&#39;, { nonNullable: true, validators: [Validators.required] }),<br>    email:    new FormControl(&#39;&#39;, { nonNullable: true, validators: [Validators.required, Validators.email] }),<br>    password: new FormControl(&#39;&#39;, { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }),<br>  });<br><br>  submit(): void {<br>    console.log(this.form.value);<br>  }<br>}</pre><p><strong>Signal Forms</strong></p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { form, FormField, required, email, minLength } from &#39;@angular/forms/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  imports: [FormField],<br>  template: `<br>    &lt;form (ngSubmit)=&quot;submit()&quot;&gt;<br>      &lt;input [formField]=&quot;f.username&quot; /&gt;<br>      &lt;input [formField]=&quot;f.email&quot; /&gt;<br>      &lt;input [formField]=&quot;f.password&quot; type=&quot;password&quot; /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Register&lt;/button&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class RegistrationComponent {<br>  model = signal({ username: &#39;&#39;, email: &#39;&#39;, password: &#39;&#39; });<br><br>  f = form(this.model, (path) =&gt; {<br>    required(path.username);<br>    required(path.email);<br>    email(path.email);<br>    required(path.password);<br>    minLength(path.password, 8);<br>  });<br><br>  submit(): void {<br>    console.log(this.model());<br>  }<br>}</pre><h3>🔁 Dynamic Forms</h3><p>Real applications rarely have a fixed number of fields. A form that lets users add multiple phone numbers, skills, or shipping addresses is a common scenario. This is where the three approaches diverge most visibly.</p><h4>Template-driven: plain array with @for</h4><p>Template-driven Forms have no built-in construct for managing dynamic arrays. The standard approach is to keep a plain array in the component and iterate over it with Angular’s @for block.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-phone-list&#39;,<br>  imports: [FormsModule],<br>  template: `<br>    @for (phone of phones; track $index) {<br>      &lt;div&gt;<br>        &lt;input [name]=&quot;&#39;phone_&#39; + $index&quot; [(ngModel)]=&quot;phones[$index]&quot; /&gt;<br>        &lt;button type=&quot;button&quot; (click)=&quot;remove($index)&quot;&gt;Remove&lt;/button&gt;<br>      &lt;/div&gt;<br>    }<br>    &lt;button type=&quot;button&quot; (click)=&quot;add()&quot;&gt;Add phone&lt;/button&gt;<br>  `<br>})<br>export class PhoneListComponent {<br>  phones: string[] = [&#39;&#39;];<br><br>  add(): void {<br>    this.phones.push(&#39;&#39;);<br>  }<br><br>  remove(index: number): void {<br>    this.phones.splice(index, 1);<br>  }<br>}</pre><p>This works for simple cases, but Angular has no awareness of the array as a unit. There is no aggregate validity, no array-level validators, and no clean way to reset the entire list programmatically.</p><h4>Reactive: FormArray</h4><p>Reactive Forms provide FormArray, a first-class construct for managing a dynamic list of controls. Each item is a full FormControl, which means it participates in validation, state tracking, and the overall form validity.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-phone-list&#39;,<br>  imports: [ReactiveFormsModule],<br>  template: `<br>    &lt;form [formGroup]=&quot;form&quot;&gt;<br>      &lt;div formArrayName=&quot;phones&quot;&gt;<br>        @for (ctrl of phones.controls; track $index) {<br>          &lt;div&gt;<br>            &lt;input [formControlName]=&quot;$index&quot; /&gt;<br>            @if (ctrl.invalid &amp;&amp; ctrl.touched) {<br>              &lt;span&gt;Phone number is required.&lt;/span&gt;<br>            }<br>            &lt;button type=&quot;button&quot; (click)=&quot;remove($index)&quot;&gt;Remove&lt;/button&gt;<br>          &lt;/div&gt;<br>        }<br>      &lt;/div&gt;<br>      &lt;button type=&quot;button&quot; (click)=&quot;add()&quot;&gt;Add phone&lt;/button&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class PhoneListComponent {<br>  form = new FormGroup({<br>    phones: new FormArray([<br>      new FormControl(&#39;&#39;, { nonNullable: true, validators: [Validators.required] })<br>    ])<br>  });<br><br>  get phones(): FormArray {<br>    return this.form.controls.phones;<br>  }<br><br>  add(): void {<br>    this.phones.push(<br>      new FormControl(&#39;&#39;, { nonNullable: true, validators: [Validators.required] })<br>    );<br>  }<br><br>  remove(index: number): void {<br>    this.phones.removeAt(index);<br>  }<br>}</pre><p>The array is a first-class citizen. this.phones.valid reflects the validity of all items at once. Adding and removing controls is explicit and synchronous.</p><p>The cost is verbosity: every add() call must manually instantiate a control and re-wire its validators. The logic lives in the component, not in the schema.</p><h4>Signal Forms: model-driven arrays with applyEach()</h4><p>Signal Forms take a different approach entirely. There is no FormArray class to instantiate. Dynamic fields are just arrays in your model signal. When you push or splice that array, the form reacts automatically.</p><p>Schema rules for each item are declared once using applyEach(). They apply to every element, including items added after form creation.</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { form, FormField, applyEach, required } from &#39;@angular/forms/signals&#39;;<br><br>interface RegistrationModel {<br>  username: string;<br>  phones: string[];<br>}<br><br>@Component({<br>  selector: &#39;app-phone-list&#39;,<br>  imports: [FormField],<br>  template: `<br>    @for (phone of f.phones; track $index) {<br>      &lt;div&gt;<br>        &lt;input [formField]=&quot;phone&quot; /&gt;<br>        @if (phone().invalid() &amp;&amp; phone().touched()) {<br>          &lt;span&gt;Phone number is required.&lt;/span&gt;<br>        }<br>        &lt;button type=&quot;button&quot; (click)=&quot;remove($index)&quot;&gt;Remove&lt;/button&gt;<br>      &lt;/div&gt;<br>    }<br>    &lt;button type=&quot;button&quot; (click)=&quot;add()&quot;&gt;Add phone&lt;/button&gt;<br>  `<br>})<br>export class PhoneListComponent {<br>  model = signal&lt;RegistrationModel&gt;({ username: &#39;&#39;, phones: [&#39;&#39;] });<br><br>  f = form(this.model, (path) =&gt; {<br>    applyEach(path.phones, (phone) =&gt; {<br>      required(phone);<br>    });<br>  });<br><br>  add(): void {<br>    this.model.update(m =&gt; ({ ...m, phones: [...m.phones, &#39;&#39;] }));<br>  }<br><br>  remove(index: number): void {<br>    this.model.update(m =&gt; ({<br>      ...m,<br>      phones: m.phones.filter((_, i) =&gt; i !== index)<br>    }));<br>  }<br>}</pre><p>No class to instantiate per item. No manual validator wiring on each add. You update the model signal, and the form structure catches up automatically.</p><blockquote><em>💡 </em><strong><em>The key insight</em></strong><em> In Signal Forms, the model signal is the source of truth not a parallel data structure you maintain alongside it. This is what “model-driven” actually means in practice.</em></blockquote><h3>⏳ Async Validation</h3><p>Some validation rules cannot run on the client alone. Checking whether a username is already taken, verifying a tax ID, or validating a coupon code all require a server round-trip.</p><p>Angular supports async validators across all three approaches, but the ergonomics differ significantly.</p><h4>A note on structure</h4><p>In the examples below, the validator logic is kept separate from the display component. This is intentional. The component renders the form; the validator enforces a rule. They are two different responsibilities, and keeping them separate makes both easier to test.</p><h4>Template-driven: custom async directive</h4><p>Template-driven Forms have no built-in async validator API. You create a directive that implements AsyncValidator and registers itself via NG_ASYNC_VALIDATORS.</p><pre>import { Directive, inject } from &#39;@angular/core&#39;;<br>import { AbstractControl, AsyncValidator, NG_ASYNC_VALIDATORS, ValidationErrors } from &#39;@angular/forms&#39;;<br>import { Observable, of, timer, switchMap, map, catchError } from &#39;rxjs&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Directive({<br>  selector: &#39;[uniqueUsername]&#39;,<br>  providers: [<br>    { <br>      provide: NG_ASYNC_VALIDATORS, <br>      useExisting: UniqueUsernameDirective, <br>      multi: true <br>    }<br>  ]<br>})<br>export class UniqueUsernameDirective implements AsyncValidator {<br>  private userService = inject(UserService);<br><br>  validate(control: AbstractControl): Observable&lt;ValidationErrors | null&gt; {<br>    if (!control.value) return of(null);<br>    return timer(400).pipe(<br>      switchMap(() =&gt; this.userService.checkUsername(control.value)),<br>      map(isTaken =&gt; isTaken ? { usernameTaken: true } : null),<br>      catchError(() =&gt; of(null))<br>    );<br>  }<br>}</pre><p>The directive is applied as an attribute on the input, and Angular picks it up through the NG_ASYNC_VALIDATORS token:</p><pre>&lt;input name=&quot;username&quot; [(ngModel)]=&quot;model.username&quot; uniqueUsername /&gt;</pre><p>The pending state is accessible via the #ngModel template reference, but reading and displaying it in the template requires extra ceremony compared to Reactive Forms.</p><h4>Reactive: asyncValidators option</h4><p>Reactive Forms accept async validators directly on a control, alongside sync validators. The control enters pending state while the validator runs — the same pending state you saw in Part 3.</p><p>The validator is a standalone factory function. The component wires it in:</p><pre>// unique-username.validator.ts<br>import { AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;<br>import { Observable, of, timer, switchMap, map, catchError } from &#39;rxjs&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>export function uniqueUsernameValidator(userService: UserService) {<br>  return (control: AbstractControl): Observable&lt;ValidationErrors | null&gt; =&gt; {<br>    if (!control.value) return of(null);<br><br>    return timer(400).pipe(<br>      switchMap(() =&gt; userService.checkUsername(control.value)),<br>      map(isTaken =&gt; isTaken ? { usernameTaken: true } : null),<br>      catchError(() =&gt; of(null))<br>    );<br>  };<br>}</pre><pre>// registration.component.ts<br>import { Component, inject } from &#39;@angular/core&#39;;<br>import { FormControl, ReactiveFormsModule, Validators } from &#39;@angular/forms&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br>import { uniqueUsernameValidator } from &#39;./unique-username.validator&#39;;<br><br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  imports: [ReactiveFormsModule],<br>  template: `<br>    &lt;input [formControl]=&quot;username&quot; /&gt;<br>    @if (username.pending) {<br>      &lt;span&gt;Checking availability...&lt;/span&gt;<br>    }<br>    @if (username.invalid &amp;&amp; username.touched &amp;&amp; !username.pending) {<br>      @if (username.hasError(&#39;required&#39;)) { &lt;span&gt;Username is required.&lt;/span&gt; }<br>      @if (username.hasError(&#39;usernameTaken&#39;)) { &lt;span&gt;Username is already taken.&lt;/span&gt; }<br>    }<br>  `<br>})<br>export class RegistrationComponent {<br>  private userService = inject(UserService);<br><br>  username = new FormControl(&#39;&#39;, {<br>    nonNullable: true,<br>    validators: [Validators.required],<br>    asyncValidators: [uniqueUsernameValidator(this.userService)],<br>    updateOn: &#39;blur&#39;<br>  });<br>}</pre><p>updateOn: &#39;blur&#39; defers the entire validation cycle — including async validators — until the user leaves the field. This replaces the need for an internal timer() debounce; do not use both at the same time or you will double-delay the response.</p><h4>Signal Forms: validateHttp()</h4><p>Signal Forms provide validateHttp() for HTTP-based async validation. Pending requests are cancelled automatically when the field value changes — no switchMap, no takeUntil.</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { form, FormField, required, validateHttp } from &#39;@angular/forms/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  imports: [FormField],<br>  template: `<br>    &lt;input [formField]=&quot;f.username&quot; /&gt;<br>    @if (f.username().pending()) {<br>      &lt;span&gt;Checking availability...&lt;/span&gt;<br>    }<br>    @if (f.username().invalid() &amp;&amp; f.username().touched() &amp;&amp; !f.username().pending()) {<br>       @for (error of f.username().errors(); track $index) {<br>          &lt;span&gt;{{ error.message }}&lt;/span&gt;<br>       }<br>    }<br>  `<br>})<br>export class RegistrationComponent {<br>  model = signal({ username: &#39;&#39; });<br><br>  f = form(this.model, (path) =&gt; {<br>    required(path.username, { message: &#39;Username is required.&#39; });<br>    validateHttp(path.username, {<br>      request: ({ value }) =&gt; `/api/check-username?q=${encodeURIComponent(value())}`,<br>      onSuccess: (response: { taken: boolean }) =&gt;<br>        response.taken<br>          ? { kind: &#39;usernameTaken&#39;, message: &#39;Username is already taken.&#39; }<br>          : null,<br>      onError: () =&gt; ({ kind: &#39;networkError&#39;, message: &#39;Could not check the username.&#39; }),<br>      debounce: 400<br>    });<br>  });<br>}</pre><p>Three things stand out compared to the Reactive approach:</p><ul><li>No switchMap boilerplate. Cancellation is handled by the framework.</li><li>debounce is a first-class option in the validator itself, not a separate RxJS operator applied externally.</li><li>Errors are mapped declaratively in onSuccess and onError, right next to the validator definition, keeping the schema self-contained.</li><li>request returns a URL (or an HttpResourceRequest), not an Observable. validateHttp() runs it through an httpResource() for you, so there is no HttpClient to inject.</li></ul><blockquote><em>💡 </em><strong><em>validateHttp() vs </em></strong><strong><em>validateAsync()</em></strong><em> Use </em><em>validateHttp() when your validation calls an Angular </em><em>HttpClient endpoint. Use </em><em>validateAsync() when you need a custom </em><em>resource() factory — third-party APIs, WebSocket checks, or any async logic that does not fit a simple HTTP GET.</em></blockquote><h3>🧩 Custom Controls</h3><p>Sometimes a native HTML input is not enough. A star rating, a rich text editor, a date picker, a PIN input — these are components that need to behave like form controls but are not built-in HTML elements.</p><p>Angular has always had an answer to this. In v22, there are now two answers, and the difference is stark.</p><h4>Reactive / Template-driven: ControlValueAccessor and Validator</h4><p>ControlValueAccessor is the interface that lets Angular treat a component as a form input. It requires four methods and a provider registration.</p><p>For cases where the custom control also needs to participate in validation — for example, a rating input that enforces a minimum selection — you add Validator to the implements clause and register via NG_VALIDATORS alongside NG_VALUE_ACCESSOR. Both tokens use forwardRef to reference the class before it is fully initialized.</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;;<br>import {<br>  AbstractControl,<br>  ControlValueAccessor,<br>  NG_VALIDATORS,<br>  NG_VALUE_ACCESSOR,<br>  ValidationErrors,<br>  Validator<br>} from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-rating-input&#39;,<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; RatingInputComponent),<br>      multi: true<br>    },<br>    {<br>      provide: NG_VALIDATORS,<br>      useExisting: forwardRef(() =&gt; RatingInputComponent),<br>      multi: true<br>    }<br>  ],<br>  template: `<br>    @for (star of stars; track star) {<br>      &lt;button<br>        type=&quot;button&quot;<br>        [class.active]=&quot;star &lt;= currentValue&quot;<br>        [disabled]=&quot;isDisabled&quot;<br>        (click)=&quot;select(star)&quot;&gt;<br>        ★<br>      &lt;/button&gt;<br>    }<br>  `<br>})<br>export class RatingInputComponent implements ControlValueAccessor, Validator {<br>  stars = [1, 2, 3, 4, 5];<br>  currentValue = 0;<br>  isDisabled = false;<br>  <br>  #onChange: (value: number) =&gt; void = () =&gt; {};<br>  #onTouched: () =&gt; void = () =&gt; {};<br>  #onValidationChange: () =&gt; void = () =&gt; {};<br>  <br>  // ControlValueAccessor<br>  writeValue(value: number): void {<br>    this.currentValue = value ?? 0;<br>  }<br>  <br>  registerOnChange(fn: (value: number) =&gt; void): void {<br>    this.onChange = fn;<br>  }<br><br>  registerOnTouched(fn: () =&gt; void): void {<br>    this.onTouched = fn;<br>  }<br><br>  setDisabledState(isDisabled: boolean): void {<br>    this.isDisabled = isDisabled;<br>  }<br><br>  // Validator<br>  validate(control: AbstractControl): ValidationErrors | null {<br>    return control.value &gt;= 1 ? null : { ratingRequired: true };<br>  }<br><br>  registerOnValidatorChange(fn: () =&gt; void): void {<br>    this.onValidationChange = fn;<br>  }<br><br>  // User interaction<br>  select(star: number): void {<br>    this.currentValue = star;<br>    this.onChange(star);<br>    this.onTouched();<br>    this.onValidationChange();<br>  }<br>}</pre><p>The parent form does not need any extra validator — the control validates itself:</p><pre>// registration.component.ts<br>form = new FormGroup({<br>  rating: new FormControl(0, { nonNullable: true })<br>  // no external Validators.min(1) needed — RatingInputComponent handles it internally<br>});</pre><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;app-rating-input formControlName=&quot;rating&quot; /&gt;<br>  @if (form.controls.rating.hasError(&#39;ratingRequired&#39;) &amp;&amp; form.controls.rating.touched) {<br>    &lt;span&gt;Please select a rating.&lt;/span&gt;<br>  }<br>&lt;/form&gt;</pre><p>This is the full CVA pattern: NG_VALUE_ACCESSOR makes the component behave as an input; NG_VALIDATORS makes it a first-class participant in the form&#39;s validity tree. The onValidationChange() call in select() is what tells Angular to re-run validation immediately after a user interaction — without it, the parent form would not react to the rating change until the next change detection cycle.</p><p>It works. But the forwardRef, the four interface methods, the manual onValidationChange callback, and the dual provider registration add up to a significant amount of boilerplate — especially when the underlying UI logic is straightforward.</p><h4>Signal Forms: FormValueControl</h4><p>Angular v22 introduces FormValueControl, the Signal Forms alternative to ControlValueAccessor. The contract is much simpler: expose a value = model&lt;TValue&gt;() signal, and the FormField directive will keep it in sync with the bound field automatically.</p><pre>import { Component, input, model } from &#39;@angular/core&#39;;<br>import { FormValueControl } from &#39;@angular/forms/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-rating-input&#39;,<br>  template: `<br>    @for (star of stars; track star) {<br>      &lt;button<br>        type=&quot;button&quot;<br>        [class.active]=&quot;star &lt;= value()&quot;<br>        [disabled]=&quot;disabled()&quot;<br>        (click)=&quot;select(star)&quot;&gt;<br>        ★<br>      &lt;/button&gt;<br>    }<br>  `<br>})<br>export class RatingInputComponent implements FormValueControl&lt;number&gt; {<br>  stars = [1, 2, 3, 4, 5];<br>  <br>  // Required by FormValueControl - FormField keeps this in sync with the field tree<br>  value = model&lt;number&gt;(0);<br>  <br>  // Optional - FormField binds these automatically when declared<br>  disabled = input&lt;boolean&gt;(false);<br>  touched  = model&lt;boolean&gt;(false);<br>  <br>  select(star: number): void {<br>      this.value.set(star);<br>      this.touched.set(true);<br>  }<br>}</pre><p>No forwardRef. No providers array. No writeValue, registerOnChange, or registerOnTouched.</p><p>The value signal is the entire contract. FormField writes to it when the model changes programmatically, and reads from it when the user interacts. Validation lives in the parent schema, exactly where it belongs:</p><pre>// registration.component.ts<br>import { min } from &#39;@angular/forms/signals&#39;;<br><br>f = form(this.model, (path) =&gt; {<br>  min(path.rating, 1);  // validation stays in the schema, not in the control<br>});</pre><pre>&lt;app-rating-input [formField]=&quot;f.rating&quot; /&gt;<br><br>@if (f.rating().invalid() &amp;&amp; f.rating().touched()) {<br>  &lt;span&gt;Please select a rating.&lt;/span&gt;<br>}</pre><blockquote><em>💡 </em><strong><em>Validation belongs in the schema, not in the control.</em></strong><em> With </em><em>ControlValueAccessor + Validator, the control was responsible for both rendering and validation. </em><em>FormValueControl separates those concerns cleanly: the component renders, the schema validates.</em></blockquote><h3>🧠 Architectural Comparison (Quick Take)</h3><p>After four parts, the differences are clear enough to be honest about.</p><p><a href="https://angular.dev/guide/forms/template-driven-forms">Template-driven Forms</a> struggle at this level of complexity. Dynamic arrays have no framework support, async validation requires a custom directive, and custom controls still go through the full ControlValueAccessor boilerplate. They remain a reasonable choice for small, self-contained forms — but once a form needs @for, server-side checks, and custom inputs at the same time, the seams start to show.</p><p><a href="https://angular.dev/guide/forms/reactive-forms">Reactive Forms</a> handle all of it well. FormArray, asyncValidators, and ControlValueAccessor + Validator are mature, stable, and well understood across the ecosystem. The cost is always the same: verbosity. Every dynamic control has to be manually instantiated and wired, every async validator needs its own RxJS chain, every custom control needs four interface methods and two providers. It is explicit by design — and in large, long-lived codebases, that explicitness pays off.</p><p><a href="https://angular.dev/guide/forms/signals/overview">Signal Forms</a> are production-ready from v22, and at this level of complexity they are the cleaner option for new code. applyEach() removes the per-item wiring entirely. validateHttp() handles debounce and cancellation out of the box. FormValueControl reduces a custom input to a single model() signal. The architecture is leaner because the schema is the single place where structure, validation, and rules live together.</p><p>If you are maintaining an existing application, Reactive Forms are not going anywhere and there is no urgency to migrate. If you are starting something new today, Signal Forms are the direction Angular is heading — and the API is now stable enough to bet on.</p><h3>🔀 Migration and Coexistence</h3><p>You do not have to rewrite everything — and you probably should not.</p><p>Angular v22 ships @angular/forms/signals/compat, which provides the compatForm bridge. This lets Signal Forms and Reactive Forms coexist in the same application, even within the same parent form.</p><p>A practical strategy for existing applications:</p><ul><li>New forms: build with Signal Forms from the start.</li><li>Existing simple forms: leave them as-is. The cost of migration rarely justifies the benefit.</li><li>Existing complex forms with custom controls: migrate the custom controls to FormValueControl first. A FormValueControl works with Reactive Forms as-is (formControlName), so the parent form stays untouched and you get the cleaner API at the component level. When you later move the parent to Signal Forms, compatForm lets it keep the Reactive controls you haven’t migrated yet.</li><li>Everything else: Signal Forms import from a separate entry point (@angular/forms/signals), so there is no risk of accidental interference with existing code.</li></ul><blockquote><em>⚠️ Do not mix </em><em>@angular/forms and </em><em>@angular/forms/signals imports in the same component unless you are explicitly using the compat bridge. The two systems are not interchangeable.</em></blockquote><h3>🚀 The Complete Picture</h3><p>This series covered Angular forms from the ground up:</p><ul><li>Part 1 — <a href="https://medium.com/@giorgio.galassi/angular-forms-model-setup-and-ui-binding-part-1-8143b8b58fdf">Model Setup and UI Binding</a>: where the model lives and how it connects to the template</li><li>Part 2 — <a href="https://medium.com/@giorgio.galassi/angular-forms-data-flow-and-working-with-inputs-part-2-006f623a45ea">Data Flow and Working with Inputs</a>: how data moves between the view and the component logic at runtime</li><li>Part 3 — <a href="https://medium.com/@giorgio.galassi/angular-forms-validation-and-form-state-part-3-0f2db5b4961e">Validation and Form State</a>: built-in validators, error display, and state signals in production</li><li>Part 4 — Advanced Patterns (this article): dynamic fields, async validation, custom controls, and coexistence</li></ul><p>One thread runs through all four parts: Angular forms have always been about the same set of problems — capturing user input, validating it, and keeping the UI in sync. What changes across Template-driven, Reactive, and Signal Forms is the philosophy behind solving those problems, not the problems themselves.</p><p>If you want to take Signal Forms further, particularly around schema-first validation with Zod and runtime boundaries, I covered that in detail in a separate article:</p><p><a href="https://blog.stackademic.com/angular-v21-runtime-validation-with-zod-schemas-signals-and-boundaries-f1ddbcb208b1">Angular v21 — Runtime Validation with Zod: Schemas, Signals, and Boundaries 🔥🚀</a></p><p>You can explore all the examples shown in this article in the associated ⚡ <a href="https://stackblitz.com/~/github.com/giorgiogalassi/angular-forms-validation-and-form-state-p4">StackBlitz project</a>.</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> and <a href="https://medium.com/@giorgio.galassi">Medium</a> for more deep dives into Angular, web performance, and modern frontend development.</p><p>See you in the next one! 🤙🏻<br> — G.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1de423db0671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Engineering: Stateless by Default, Stateful by Design ]]></title>
            <link>https://medium.com/@giorgio.galassi/context-engineering-stateless-by-default-stateful-by-design-ce5883a64dfb?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5883a64dfb</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-06-19T06:20:50.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RK1SEO_ZuSyqk6dc" /></figure><p>Let’s be honest: you’ve explained the same thing to your coding agent more than once this week. The project structure. The naming conventions. The decision you made three weeks ago about which approach to take. The agent asked, you answered, the session closed — and the next morning you started from zero.</p><p>This is not a prompt problem. It’s a design problem.</p><h3>🔍 Prompt Engineering vs. Context Engineering</h3><p>Prompt engineering gets most of the attention. It’s visible, immediate, and feels like leverage. But there’s a distinction worth making explicit:</p><p><strong>Prompt engineering</strong> is what you say to the agent.</p><p><strong>Context engineering</strong> is what the agent already knows before you say anything.</p><p>Context is upstream of every prompt you’ll ever write. If the agent starts cold, no amount of clever prompting fully compensates. The higher-leverage skill — the one most developers skip — is deciding what your agents know, when they know it, and how that knowledge survives session boundaries and tool switches.</p><h3>💥 What Happens When Context Isn’t Managed</h3><p>The research community has named the failure modes:</p><p><strong>Context confusion</strong> happens when too many tool definitions compete for space. One study found a model failed completely with 46 tools available, and worked fine trimmed to 19. The context wasn’t too long — it was too crowded.</p><p><strong>Context distraction</strong> is what happens when accumulated conversation history causes the model to echo recent noise instead of reasoning from first principles. The agent stops thinking and starts pattern-matching on what just happened.</p><p><strong>Context poisoning</strong> is the silent one. Stale decisions, superseded architecture notes, outdated requirements — all sitting in context alongside current work. The agent builds on bad foundations.</p><p><strong>Context rot</strong> is the gradient, not the cliff. <a href="https://www.trychroma.com/research/context-rot">Chroma tested 18 frontier models in 2025</a>. Every single one got worse as input length grew — and the degradation started well before the stated context limit. A model with a 200k token window may show meaningful decline at 50k tokens. You don’t get an error. You get a subtly wrong answer.</p><h3>🔧 Four Techniques That Actually Work</h3><h3>1. Index-First Loading</h3><p>Before reading anything else, load one small file that orients the agent: what project is this, what was the last decision, where did things stand. A dispatch table, not a document.</p><pre>## Active project: payments-refactor<br><br>Goal: redesign the checkout flow<br>Last session: explored three approaches, settled on progressive disclosure<br>Next: stress-test the approach, identify edge cases</pre><p>The agent resumes instantly. No re-explanation needed. There’s also a structural reason to load critical content first: <a href="https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00638/119630/Lost-in-the-Middle-How-Language-Models-Use-Long">research published in TACL</a> shows models recall information best from the start and end of context, with accuracy dropping 30+ points when relevant content sits in the middle. As a side effect, stable content loaded first also maximizes prompt cache hits — index-first loading is cache-first loading.</p><h3>2. Anchored Iterative Summarization</h3><p>At the end of every session, rewrite your state document. Not append — overwrite. A fixed structure: goal, explored, open questions. Always in the same place.</p><p>Logs are for humans. State documents are for agents. If you append, the document grows into a log. Logs are expensive. An overwritten state document stays bounded, stays useful, stays cheap to load.</p><h3>3. Phase-Based Context Loading</h3><p>The agent doesn’t need everything at once. Loading everything upfront wastes context space you’ll want later.</p><p>Phase What loads Orientation Index file + state document Task Relevant specs + architecture notes Implementation Specific files being modified</p><p>Start minimal. Load more as the task demands it. Three phases, three cost levels, no waste.</p><h3>4. Just-In-Time File Retrieval</h3><p>When implementing one module, the agent doesn’t need the full session history or every architecture document. Load files at the moment they’re needed, not before. Everything else stays on disk.</p><p>Combined, these four techniques change the default: from “context fills with everything that happened” to “context contains exactly what the current step requires.”</p><h3>🗂️ Where Should Memory Live?</h3><p>Before reaching for infrastructure, there’s a decision worth making explicitly:</p><p><strong>Inside the tool</strong> is the easiest start — but your memory is now vendor-owned. Switch tools, lose memory.</p><p><strong>Inside the repo</strong> feels natural and keeps things version-controlled, but architectural decisions end up in git alongside source code, and get archived with the project.</p><p><strong>Outside both</strong> is the most resilient option. Your knowledge layer is independent of any tool, any repo, any vendor. It requires discipline to maintain, and it’s the only option that survives long-term.</p><p>There’s no universally right answer. But there’s a useful question to ask before reaching for a vector store or a managed memory API: do I have a search problem, or a retrieval problem? Most context engineering scenarios are retrieval — you know exactly which file you need. A filesystem with discipline is often enough.</p><h3>🎯 What This Unlocks</h3><p>For a single developer: resume a feature after three days with no re-explanation. Switch models without losing anything — the context travels with you, not with the tool.</p><p>At larger scale: a team sharing context across sessions and members; multiple tools reading the same memory layer; a shared MCP server all tools write to. The discipline is the same. What changes is the write layer.</p><p>This is no longer a niche concern. <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Anthropic’s engineering team</a> published their approach to context engineering for agents in late 2025, covering compaction, structured note-taking, and multi-agent architectures with clean context windows. <a href="https://github.com/neurontist/Google-AI-Agents-Intensive-2025/blob/main/Context%20Engineering:%20Sessions%20%26%20Memory.md">Google’s Sessions &amp; Memory whitepaper</a> frames the same discipline as “dynamically assembling and managing information within the context window to create stateful, personalized AI experiences.”</p><p>The tools are already there. The models are already capable enough.</p><p>Context engineering is not something you install. It’s how you think about what your agents know.</p><p>If you found this useful, follow me on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> and <a href="https://medium.com/@giorgio.galassi">Medium</a> — more on AI workflows and agent architecture coming.</p><p>See you in the next one! 🤙🏻 <br>— G.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5883a64dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular WebMCP — Your App is Now an AI Tool ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-webmcp-your-app-is-now-an-ai-tool-6b36c93b3b20?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b36c93b3b20</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-06-15T07:01:02.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xgkd1ylM6uXgTM4o" /></figure><p>There’s a pattern in Angular releases that I’ve come to appreciate: every major version picks one bet that’s slightly ahead of its time. Signals were that bet in v16. Zoneless was that bet in v21. In v22, that bet is <a href="https://angular.dev/ai/webmcp"><strong>WebMCP</strong></a>, and it’s a fundamentally different kind of feature — not a framework improvement, but an architectural shift in what an Angular app <em>is</em>.</p><p>Let me explain what I mean.</p><h3>🧭 The Idea: Outside → In</h3><p>Every Angular feature so far has been about what happens <em>inside</em> the app — how components detect changes, how services are injected, how forms manage state. WebMCP is different: it’s about exposing your app’s capabilities to the <em>outside</em>, specifically to AI agents running in the browser.</p><p>The mental model is simple. Today, an AI assistant browsing your app sees a DOM — pixels and HTML. It can read text and click buttons, but it has no understanding of what your app <em>can do</em>. WebMCP changes that. You declare a set of tools backed by your real Angular services, your real signals, your real DI graph, and any WebMCP-capable agent can discover and call them directly through a typed, described interface you control.</p><p>This is different from <a href="https://angular.dev/ai/agent-skills"><strong>Agent Skills</strong></a>, which is your app calling <em>out</em> to AI. Two separate features, two directions: WebMCP is agents driving your app; Agent Skills is your app calling AI. Today we’re only talking about WebMCP.</p><h3>🔧 Browser Support</h3><p>WebMCP is built on the <a href="https://github.com/webmachinelearning/webmcp/"><strong>W3C ModelContext API</strong></a>, a draft browser standard. Your tools register on document.modelContext and any agent that speaks this protocol can query that object and call them.</p><p>As of June 2026, Edge 147 ships it natively, Chrome 149 has an open Origin Trial, Firefox is committed for Q3 2026, and Safari for Q4. Mass adoption is realistically mid-2027, and Angular ships this as experimental — that flag is honest, but the integration is already surprisingly clean.</p><blockquote><em>⚠️ </em><strong><em>Experimental:</em></strong><em> </em><a href="https://angular.dev/api/core/provideExperimentalWebMcpTools"><em>provideExperimentalWebMcpTools()</em></a><em> is available in Angular 22 but carries no stability guarantees yet. The W3C spec is still evolving; expect API changes before general availability.</em></blockquote><h3>🛠️ Building Your First WebMCP Tool</h3><p>Let’s build something concrete. A dashboard shows a list of expenses and we want an AI assistant to ask “what expenses are currently visible?” and get real, live data back — not a DOM scrape or a static API response, but the actual signal state the component is rendering from.</p><h3>Step 1: The service</h3><pre>// expense.service.ts<br>import { Service, signal } from &#39;@angular/core&#39;;<br><br>export interface Expense {<br>  id: string;<br>  description: string;<br>  amount: number;<br>  currency: string;<br>  category: ExpenseCategory;<br>}<br><br>export const ExpenseCategory = {<br>  Accommodation: &#39;accommodation&#39;,<br>  Transport: &#39;transport&#39;,<br>  Meals: &#39;meals&#39;,<br>} as const;<br><br>export type ExpenseCategory = typeof ExpenseCategory[keyof typeof ExpenseCategory];<br><br>export const CATEGORY_VALUES = Object.values(ExpenseCategory).join(&#39;, &#39;);<br><br>@Service()<br>export class ExpenseService {<br>  private expenses = signal&lt;Expense[]&gt;([<br>    { id: &#39;1&#39;, description: &#39;Hotel&#39;,  amount: 250, currency: &#39;USD&#39;, category: ExpenseCategory.Accommodation },<br>    { id: &#39;2&#39;, description: &#39;Taxi&#39;,   amount: 35,  currency: &#39;USD&#39;, category: ExpenseCategory.Transport },<br>    { id: &#39;3&#39;, description: &#39;Dinner&#39;, amount: 80,  currency: &#39;USD&#39;, category: ExpenseCategory.Meals },<br>  ]);<br><br>  getVisible(): Expense[] {<br>    return this.expenses();<br>  }<br>}</pre><p>@Service() is Angular 22&#39;s new shorthand for @Injectable({ providedIn: &#39;root&#39; }) — if you want the full picture on that, I covered it in <a href="https://medium.com/@giorgio.galassi/angular-22-service-and-injectasync-dependency-injection-finally-grows-up-499e508fa47c">Angular 22 — @Service and injectAsync: Dependency Injection Finally Grows Up</a>. Notice that CATEGORY_VALUES lives right here next to the ExpenseCategory object — we&#39;ll use it to keep the tool description in sync automatically.</p><h3>Step 2: Declaring the tool</h3><p>Parameters are described using <a href="https://json-schema.org/">JSON Schema</a> syntax — the same format Angular uses internally and the same format the agent receives.</p><pre>// expense-mcp.tool.ts<br>import { declareExperimentalWebMcpTool, inject } from &#39;@angular/core&#39;;<br>import { ExpenseService, ExpenseCategory, CATEGORY_VALUES } from &#39;./expense.service&#39;;<br><br>export const expenseListTool = declareExperimentalWebMcpTool({<br>  name: &#39;getVisibleExpenses&#39;,<br>  description: &#39;Returns the list of expenses currently visible in the dashboard.&#39;,<br>  inputSchema: {<br>    type: &#39;object&#39;,<br>    properties: {<br>      category: {<br>        type: &#39;string&#39;,<br>        description: `Filter by expense category. Allowed values: ${CATEGORY_VALUES}.`,<br>      },<br>    },<br>    additionalProperties: false,<br>  },<br>  execute: ({ category }: { category?: ExpenseCategory }) =&gt; {<br>    const svc = inject(ExpenseService);<br>    const all = svc.getVisible();<br>    const filtered = category ? all.filter(e =&gt; e.category === category) : all;<br>    <br>    return { content: [{ type: &#39;text&#39;, text: JSON.stringify(filtered) }] };<br>  }<br>});</pre><p>Four things to notice here.</p><p><strong>The return value follows the MCP tool result format.</strong> { content: [{ type: &#39;text&#39;, text: &#39;...&#39; }] } is the wire format the agent expects, defined by the Model Context Protocol spec. You don&#39;t return a plain object or array directly — you serialise your data into that text field with JSON.stringify, and the agent parses it on its end. This is not Angular-specific; it&#39;s the protocol contract every MCP tool must honour.</p><p><strong>name and </strong><strong>description are instructions to the LLM</strong>, not documentation for humans. The agent reads them at runtime to decide whether and how to call the tool, so write them like an OpenAPI spec for an AI: precise, specific, unambiguous.</p><p><strong>execute runs inside Angular&#39;s injection context</strong>, which means inject() works normally and your tool has full access to your DI graph.</p><p><strong>CATEGORY_VALUES is derived from the object, not hardcoded.</strong> Add a value to ExpenseCategory and the agent description updates automatically, with no second place to maintain.</p><h3>Step 3: Registering in the app</h3><pre>// app.config.ts<br>import { provideExperimentalWebMcpTools } from &#39;@angular/core&#39;;<br>import { expenseListTool } from &#39;./expense-mcp.tool&#39;;<br><br>export const appConfig = {<br>  providers: [<br>    provideExperimentalWebMcpTools([expenseListTool]),<br>    // ... rest of your providers<br>  ]<br>};</pre><p>One line in your app config and you’re done. From here, any WebMCP-capable agent visiting your app will find getVisibleExpenses in document.modelContext.tools and can call it against the live session.</p><h3>🔍 What the Agent Actually Sees</h3><p>When a WebMCP-capable agent inspects the page, this is what it finds on document.modelContext:</p><pre>{<br>  &quot;tools&quot;: [<br>    {<br>      &quot;name&quot;: &quot;getVisibleExpenses&quot;,<br>      &quot;description&quot;: &quot;Returns the list of expenses currently visible in the dashboard.&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;category&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;description&quot;: &quot;Filter by expense category. Allowed values: accommodation, transport, meals.&quot;<br>          }<br>        },<br>        &quot;additionalProperties&quot;: false<br>      }<br>    }<br>  ]<br>}</pre><p>The user says <em>“show me only transport expenses.”</em> The agent reads the schema, resolves category: &quot;transport&quot;, calls the tool. Angular runs the handler against the live signal state. The agent gets back exactly the filtered rows the dashboard is currently showing — no DOM scraping, no brittle selectors, no static mock data.</p><h3>⚛️ Signal Forms as Agent Tools</h3><p>If your app is form-heavy, Angular 22 also ships <a href="https://angular.dev/api/forms/signals/provideExperimentalWebMcpForms">provideExperimentalWebMcpForms()</a>, which automatically surfaces all your <a href="https://angular.dev/essentials/signal-forms">Signal Forms</a> as agent-callable tools without you having to declare each one manually.</p><pre>// app.config.ts<br>import { provideExperimentalWebMcpForms } from &#39;@angular/forms/signals&#39;;<br><br>export const appConfig = {<br>  providers: [<br>    provideExperimentalWebMcpForms(),<br>  ]<br>};</pre><blockquote><em>⚠️ </em><strong><em>Experimental:</em></strong><em> </em><em>provideExperimentalWebMcpForms() is double-experimental — both WebMCP itself and the forms integration are in preview. Treat it as a proof of concept for now.</em></blockquote><p>Each Signal Form becomes a tool the agent can fill and submit. For internal tooling or admin dashboards this is already genuinely useful, and it shows where the Angular team is heading: if Signal Forms are the way to model user intent, they should also be the way to model agent intent.</p><h3>💡 Beyond the Happy Path</h3><p>The docs highlight forms as the easy entry point, but the more interesting territory is everything else — read queries, write actions, navigation triggers.</p><p>Let’s be honest: a <strong>read + write pair</strong> is where agents become genuinely powerful. Expose getExpenseReports() alongside flagExpense(id, reason) and an agent can query, reason over the data, and act in a single turn. Add permission-awareness by injecting your AuthService inside the execute handler and the agent automatically gets a properly scoped view, seeing only what the current user is authorised to see. You could also expose derived data tools like getSummaryByCategory() — pre-computed aggregates cost fewer tokens and produce faster responses than handing the agent a raw list to process itself.</p><p>The general principle worth internalising: anywhere you’d write a hardcoded string describing your domain model, ask whether you can derive it from TypeScript instead. Your types are the single source of truth and the agent’s schema should follow from them, not diverge from them.</p><h3>🔒 One Thing Worth Getting Right Early: Trust</h3><p>Because execute handlers run inside Angular&#39;s injection context with full access to your DI graph, a WebMCP tool is as powerful as the service method it wraps — which means a write tool is a real mutation, not a preview. Before shipping any tool that modifies state, there are three things worth understanding.</p><p><strong>Prompt injection in your descriptions.</strong> The description and parameter description fields are read by the LLM as trusted context. A malicious site can embed instructions in its own tool descriptions that manipulate the agent&#39;s behaviour on <em>other</em> sites — and if your own tool returns user-generated content, that content is another vector. The <a href="https://github.com/webmachinelearning/webmcp/blob/main/docs/security-privacy-considerations.md">W3C security considerations doc</a> calls this out explicitly under &quot;Metadata / Description Attacks&quot; and &quot;Output Injection Attacks&quot;: never echo unsanitised user content directly from an execute handler.</p><p><strong>Angular does not validate inputs for you.</strong> The agent is supposed to match the inputSchema you define, but Angular makes no guarantee it does — the execute callback receives whatever the agent sends. The <a href="https://angular.dev/ai/webmcp#validate-tool-inputs">Angular docs are explicit on this</a>: <em>&quot;Consider explicitly validating arguments to the execute function before using them.&quot;</em> Treat every input as untrusted, the same way you would a form submission or a query parameter.</p><p><strong>The session is the attack surface.</strong> The <a href="https://github.com/webmachinelearning/webmcp/blob/main/docs/security-privacy-considerations.md">W3C spec’s threat model</a> notes that agents inherit the user’s authentication context — session cookies, logged-in state, everything. The real risk isn’t an anonymous external caller; same-origin constraints handle that. The risk is a legitimate, trusted agent that has been manipulated through prompt injection and then calls your write tools with the user’s full permissions. Design accordingly: scope write tools tightly, and never expose an action you wouldn’t want triggered automatically on behalf of a logged-in user.</p><h3>⚠️ The Honest Caveat</h3><p>The <a href="https://github.com/webmachinelearning/webmcp/">W3C spec</a> is still early and has been changing frequently. Mid-2027 is the realistic mass-adoption target, when both browser default support and enough publisher adoption exist to make it meaningful at scale. For now it’s great for internal tools and early experimentation, but it’s not ready to ship to anonymous production users.</p><p>That said, the direction is set. Your app has always had one interface — the DOM, for humans. WebMCP adds a second one, for agents. How you design that second surface is a new skill worth starting to develop now, before the spec lands and everyone is catching up at once.</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, signals, AI, and modern frontend development.</p><p>See you in the next one! 🤙🏻<br><strong> — G.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b36c93b3b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular v22: @boundary, Multi-Case Switch, and Inline Arrow Functions ]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-v22-boundary-multi-case-switch-and-inline-arrow-functions-9293380f333b?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/9293380f333b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 12:54:04 GMT</pubDate>
            <atom:updated>2026-06-11T12:54:04.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvHrCZtlOAp8SNjU" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s be honest: Angular templates have been the quiet achiever of the framework’s renaissance. While everyone was rightly excited about <a href="https://angular.dev/guide/signals">Signals</a>, <a href="https://angular.dev/guide/experimental/zoneless">zoneless change detection</a>, and <a href="https://medium.com/@giorgio.galassi/angular-v19-understanding-the-new-httpresource-api-837e1dadc990">httpResource</a>, the template layer was grinding away in the background, getting smarter with every release — <a href="https://medium.com/@giorgio.galassi/angular-v18-introducing-let-a-new-way-to-declare-variables-and-do-logic-in-templates-8b3f4d196b23">@let</a>, <a href="https://medium.com/@giorgio.galassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-5a5dfaf52cd2">@defer</a>, <a href="https://angular.dev/guide/templates/control-flow">control flow blocks</a>. Angular v22 just changed the conversation again. Two features shipped, and one more is on the way and at least one of them solves a problem that&#39;s been causing production headaches for years.</p><p>Let’s break them down.</p><h3>🛡️ @boundary + @error — The Error Boundary Angular Always Needed</h3><p>If you’ve spent any time debugging production Angular apps, you’ve seen it: one component crashes during change detection, and the entire page goes white. Not just that component, but the whole page.</p><p>@boundary is Angular&#39;s answer to this. It&#39;s an error boundary primitive being built directly into the template syntax. Wrap any component in it and you get full isolation — if that subtree crashes, the rest of the page keeps rendering. Pair it with an @error block and you decide exactly what the user sees instead, and you even get access to the error object.</p><pre>@boundary {<br>  &lt;app-promotional-widget /&gt;<br>} @error (let err) {<br>  &lt;!-- err contains the caught error --&gt;<br>  &lt;app-default-promo-widget /&gt;<br>}</pre><p>This is the pattern React developers have had with ErrorBoundary for years. Angular is building it as a first-class template primitive — no wrapper components, no custom error handlers, no third-party libraries. And if @error looks familiar, that&#39;s because you&#39;ve already seen it in <a href="https://medium.com/@giorgio.galassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-5a5dfaf52cd2">@defer</a> — same concept, same block name, now elevated to a standalone boundary primitive.</p><blockquote><em>⚠️ </em><strong><em>Availability:</em></strong><em> </em><em>@boundary was first announced at Google I/O 2026 and is currently in active development starting from Angular v22. It was not shipped in v22 stable — expect it as developer preview in v22.1 or v23. Keep an eye on it, but don&#39;t wait for it in production just yet.</em></blockquote><p>The implications go beyond “nice to have.” In any app with dynamic or third-party widgets, real-time data feeds, or user-generated content blocks, @boundary will be the difference between a degraded experience and a broken one.</p><h3>🔀 Multi-Case Switch + Exhaustive Type Checking</h3><p>The @switch block already made Angular templates cleaner when it arrived — but it had a limitation: one case, one branch. If you wanted two values to render the same UI, you needed duplicate branches or a workaround.</p><p>That’s gone now. Multiple cases can share a single branch:</p><pre>@switch (status) {<br>  @case (&#39;pending&#39;)<br>  @case (&#39;queued&#39;) {<br>    &lt;status-badge type=&quot;waiting&quot; /&gt;<br>  }<br>  @case (&#39;active&#39;) {<br>    &lt;status-badge type=&quot;running&quot; /&gt;<br>  }<br>  @default {<br>    &lt;status-badge type=&quot;unknown&quot; /&gt;<br>  }<br>}</pre><p>But the more interesting addition is exhaustive type checking via @default never. When your switch expression is a TypeScript union type, adding @default never causes a compile-time error if the union grows a new member that isn&#39;t handled.</p><p>The feature originally shipped in v21.2 for simple discriminants. Angular v22 extends it to nested property access — you just pass the discriminant explicitly:</p><pre>@let data = chartData();<br>@switch (data.type) {<br>  @case (&#39;line-chart&#39;) {<br>    &lt;line-chart [data]=&quot;data&quot; /&gt;<br>  }<br>  @case (&#39;bar-chart&#39;) {<br>    &lt;bar-chart [data]=&quot;data&quot; /&gt;<br>  }<br>  @default never(data);<br>}</pre><p>For simple signals it still works without the argument:</p><pre>@switch (userRole()) {<br>  @case (&#39;admin&#39;) { ... }<br>  @case (&#39;editor&#39;) { ... }<br>  @case (&#39;viewer&#39;) { ... }<br>  @default never;<br>}</pre><p>This moves an entire class of runtime bugs — the “we added a new role and forgot to update the UI” kind — into compile time. That’s a meaningful DX win, now covering the full range of switch patterns.</p><h3>➡️ Inline Arrow Functions — Finally Official</h3><p>This one might feel smaller, but the signal it sends matters. The Angular team has officially said: inline arrow functions in templates are fine for short, non-complex expressions.</p><p>Previously, the guidance was to push any logic into the component class, even a simple (item) =&gt; item.active. That discipline made sense when templates were re-evaluated aggressively, but in a signal-driven, <a href="https://angular.dev/best-practices/skipping-subtrees">OnPush</a>-default world, the calculus changes.</p><pre>@for (user of users(); track user.id) {<br>  &lt;user-card [isAdmin]=&quot;roles().some(r =&gt; r.userId === user.id)&quot; /&gt;<br>}</pre><p>No more moving a one-liner to the component just to satisfy the “no logic in templates” rule. The team drew a clear line: short and non-complex is fine. Complex transformations still belong in <a href="https://medium.com/@giorgio.galassi/angular-v19-computed-vs-linkedsignal-signals-3130b70861b8">computed()</a> or component methods. That&#39;s a reasonable boundary, and it&#39;s one less friction point when writing clean, readable templates.</p><h3>🎯 What This Means for Your Next Project</h3><p><a href="https://blog.angular.dev/announcing-angular-v22-c52bb83a4664">Angular v22</a> stable dropped the week of June 3, 2026. With it:</p><ul><li>@default never for exhaustive switch checking, improved in v22 to work on nested property access too (@default never(entity))</li><li>Inline arrow functions — clean up those unnecessary component methods with confidence</li><li>@boundary + @error in active development, coming as developer preview in v22.1 or v23</li></ul><p>The template layer is no longer just syntactic sugar on top of component logic. It’s becoming a resilient, type-safe environment in its own right. When @boundary lands, Angular templates will have everything: crash isolation, exhaustive union safety at compile time, and signal-aligned ergonomics for everyday expressions.</p><p>If you want to go deeper on the template features that got us here, check out my previous articles:</p><ul><li><a href="https://medium.com/@giorgio.galassi/angular-v18-introducing-let-a-new-way-to-declare-variables-and-do-logic-in-templates-8b3f4d196b23">Angular v18 — Introducing </a><a href="https://medium.com/@giorgio.galassi/angular-v18-introducing-let-a-new-way-to-declare-variables-and-do-logic-in-templates-8b3f4d196b23">@let</a></li><li><a href="https://medium.com/@giorgio.galassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-5a5dfaf52cd2">Understanding </a><a href="https://medium.com/@giorgio.galassi/angular-v18-understanding-defer-blocks-triggers-and-deferrable-views-part-1-5a5dfaf52cd2">@defer — Part 1 (v18+)</a></li><li><a href="https://medium.com/@giorgio.galassi/angular-v19-understanding-defer-blocks-triggers-and-deferrable-views-part-2-cff60f89e295">Understanding </a><a href="https://medium.com/@giorgio.galassi/angular-v19-understanding-defer-blocks-triggers-and-deferrable-views-part-2-cff60f89e295">@defer — Part 2 (v19+)</a></li></ul><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/">LinkedIn</a> for more deep dives into Angular, signals, and modern frontend development.</p><p>See you in the next one! 🤙🏻 <br><strong>— G.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9293380f333b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 22 — @Service and injectAsync: Dependency Injection Finally Grows Up]]></title>
            <link>https://medium.com/@giorgio.galassi/angular-22-service-and-injectasync-dependency-injection-finally-grows-up-499e508fa47c?source=rss-892fd702c871------2</link>
            <guid isPermaLink="false">https://medium.com/p/499e508fa47c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Giorgio Galassi]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 06:56:00 GMT</pubDate>
            <atom:updated>2026-07-27T15:48:29.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fxd-FHVry3NIIvbD" /></figure><h3>Angular 22 — @Service and injectAsync: Dependency Injection Finally Grows Up 🔥🚀</h3><p>Here we are again with another Angular release that quietly removes friction you didn’t even know you’d accepted. @Injectable({ providedIn: ‘root’ }) is one of those lines. You’ve typed it so many times it became invisible, not signal, just noise. <a href="https://blog.angular.dev/announcing-angular-v22-c52bb83a4664">Angular 22</a> ships <a href="https://angular.dev/guide/di/creating-and-using-services#using-the-service-decorator">@Service(</a>), a decorator that says exactly what you mean. But the more interesting story is <a href="https://angular.dev/guide/di/lazy-loading-services">injectAsync()</a>, which finally makes lazy-loading singleton services something you’d actually do in a real project.</p><p>Let’s dig in. If you want a solid foundation on how Angular’s DI system works before reading on, I covered it in depth in my two-part series: <a href="https://medium.com/@giorgio.galassi/understanding-angular-exploring-dependency-injection-and-design-patterns-part-0-5ca21702d74b">Part 0</a> and <a href="https://medium.com/@giorgio.galassi/understanding-angular-exploring-dependency-injection-and-design-patterns-part-1-1eaaa367244b">Part 1</a>.</p><h3>🔧 @Service(): Finally, a Decorator That Says What It Means</h3><p>@Service() is shorthand for @Injectable({ providedIn: &#39;root&#39; }). Same root scope, no extra config. The one constraint: you must use inject() for dependency resolution. Constructor injection is not supported.</p><p>Nothing is better than seeing some code to understand something:</p><pre>// Before Angular 22<br>import { Injectable, inject } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  #http = inject(HttpClient);<br>  #logger = inject(LoggerService);<br>  getUser(id: string) {<br>    return this.http.get(`/api/users/${id}`);<br>  }<br>}<br><br>// Angular 22<br>import { Service, inject } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br>@Service()<br>export class UserService {<br>  #http = inject(HttpClient);<br>  #logger = inject(LoggerService);<br><br>  getUser(id: string) {<br>    return this.http.get(`/api/users/${id}`);<br>  }<br>}</pre><p>The inject()-only constraint isn&#39;t arbitrary. The Angular team has been nudging the community toward function-based injection ever since signals landed, and @Service() makes that nudge explicit and consistent. If you&#39;ve been mixing constructor injection and inject() across your codebase, this is a natural moment to standardise.</p><p><strong>When to use </strong><strong>@Service() vs </strong><strong>@Injectable</strong></p><p>@Service() covers the 80% case: a root-scoped singleton with no special provider config. Reach for @Injectable when you need useClass, useValue, useExisting, or useFactory with deps (those options have no equivalent in @Service()). For module-based injection in an NgModule context, @Injectable is still the right tool.</p><p>For everything else, @Service() has you covered, including a factory option that replaces the most common useFactory patterns. The factory runs in an injection context, so inject() works inside it. A practical example: feature-flag-based implementation switching, where you want a lightweight stub by default and the full implementation only when a token says the feature is active:</p><pre>import { inject, Service } from &#39;@angular/core&#39;;<br>import { FEATURE_FLAGS } from &#39;./tokens&#39;;<br><br>@Service({<br>  factory: () =&gt; inject(FEATURE_FLAGS).richEditor ? new RichEditorService() : new BasicEditorService(),<br>})<br>export class EditorService {<br>  insert(content: string) {<br>    // basic implementation<br>  }<br>}<br><br>class RichEditorService extends EditorService {<br>  override insert(content: string) {<br>    // full rich text implementation<br>  }<br>}</pre><p>And if you want the class to exist in the DI system but not be auto-provided at root (for example, to scope it to a specific route or component), you can opt out:</p><pre>import { Service } from &#39;@angular/core&#39;;<br><br>@Service({ autoProvided: false })<br>export class SessionTracker {<br>  #events: string[] = [];<br><br>  record(event: string) {<br>    this.events.push(event);<br>  }<br>}</pre><p>Then provide it manually in the providers array of the component or route where you need it. Each consumer gets its own isolated instance.</p><h3>🚀 injectAsync(): Lazy-Loading Singletons Without the Ceremony</h3><p>This is where Angular 22 changes architecture decisions, not just syntax.</p><p>Let’s be honest about how code-splitting a singleton service worked before this. You’d write a wrapper service to manage the dynamic import, handle the Promise manually, deal with loading state, and end up with enough boilerplate to make you question whether it was worth the effort. Most teams skipped it and just shipped everything in the initial bundle.</p><p>injectAsync() removes all of that:</p><pre>import { Component, injectAsync, onIdle, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-invoice-preview&#39;,<br>  template: `&lt;button (click)=&quot;downloadInvoice()&quot;&gt;Download Invoice&lt;/button&gt;`,<br>})<br>export class InvoicePreviewComponent {<br>  #invoice = signal&lt;Invoice | null&gt;(null);<br><br>  #invoiceExporter = injectAsync(<br>    () =&gt; import(&#39;./services/invoice-exporter.service&#39;).then(m =&gt; m.InvoiceExporterService),<br>    { prefetch: onIdle }<br>  );<br><br>  async downloadInvoice() {<br>    const exporter = await this.#invoiceExporter();<br>    exporter.export(this.#invoice()!);<br>  }<br>}</pre><p>The loader function must resolve to the service class (the ProviderToken), not the module, hence the .then(m =&gt; m.InvoiceExporterService). If your service is the <strong>default export</strong>, you can skip the .then() entirely and pass the dynamic import directly: Angular unwraps default for you.</p><pre>// service as default export<br>import { Service } from &#39;@angular/core&#39;;<br><br>@Service()<br>export default class InvoiceExporterService {<br>  export(invoice: Invoice) { /* … */ }<br>}<br><br>// consumer — no .then() needed<br>#invoiceExporter = injectAsync(() =&gt; import(&#39;./invoice-exporter.service&#39;));</pre><p>The prefetch option accepts a PrefetchTrigger, and onIdle (imported from @angular/core) tells Angular to warm the bundle during browser idle time using requestIdleCallback.</p><p>This is the key insight: { prefetch: onIdle } gives you the DX of lazy-loading with the UX of eager-loading. The bundle stays out of your initial payload, but by the time the user clicks &quot;Download Invoice,&quot; the service is already resolved. No latency hit.</p><h3>💡 What This Unlocks in Practice</h3><p>Think about the kinds of services that actually deserve to be lazy-loaded. Document exporters that most users never touch. Rich text or media editors that only appear behind a feature flag or a specific route. Heavyweight processing utilities that get triggered by a single button in a settings panel. Analytics and experimentation SDKs that belong on certain surfaces and not others. None of these need to be in your initial bundle. They just ended up there because pulling them out required more effort than most teams were willing to spend. injectAsync() makes the correct architectural decision also the easy one.</p><p>If you found this helpful, follow me here and on <a href="https://www.linkedin.com/in/giorgiogalassi/"><strong>LinkedIn</strong></a> for more deep dives into Angular, web performance, and modern frontend development.</p><p>See you in the next one! 🤙🏻<br><strong> — G</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=499e508fa47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>