<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 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">
  <channel>
    <title>Angular University</title>
    <link>https://blog.angular-university.io/</link>
    <description>Learn and Keep Up with the Angular Ecosystem</description>
    <language>en</language>
    <atom:link href="https://blog.angular-university.io/rss/" rel="self" type="application/rss+xml"/>
    <lastBuildDate>Thu, 15 Oct 2026 12:32:29 GMT</lastBuildDate>
    <item>
      <title>Angular Router with Signals: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-router-with-signals/</link>
      <guid isPermaLink="false">6ad0c34c96d69a000144cf63</guid>
      <pubDate>Thu, 15 Oct 2026 12:32:29 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Router</category>
      <description>Explore the Angular Router through its signal-based APIs and bring the power of signals to your application&#39;s routing.</description>
      <content:encoded><![CDATA[<p>Did you know that the Angular Router already supports a complete signals-only approach to most of its features?</p>
<p>You might not even have noticed it, because most of it is based purely on <strong>opt-in configuration and naming conventions</strong>!</p>
<p>The fact is that you no longer have to use the old Observable-based APIs, such as <code>ActivatedRoute</code>, <code>ActivatedRouteSnapshot</code>, etc. that can feel a bit cumbersome.</p>
<p>With the signal integration, everything works in a much more seamless and intuitive way.</p>
<p>The problem is that the old and new APIs exist side by side, so it's very easy to mix them up accidentally.</p>
<p>To really highlight the new APIs of the Angular Router, we are going to explore it from a signals perspective only.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>Router setup for a signals-first approach</li>
<li>Path parameters as signal inputs</li>
<li>Query parameters as signal inputs</li>
<li>Route resources data as signal inputs</li>
<li>Active navigation with isActive</li>
<li>Navigation status with currentNavigation</li>
<li>Tracking the last successful navigation</li>
<li>Conclusions and Key Takeaways</li>
</ul>
<p>So without further ado, let's get started with our Angular Router with Signals deep dive.</p>
<h2 id="router-setup-for-a-signals-first-approach">Router setup for a signals-first approach</h2>
<p>The use of signals does not change the very basics of routing. We still need a route configuration, a registered router, an outlet, etc.</p>
<p>Most of the signal-based magic sauce comes from the use of the <strong><code>withComponentInputBinding()</code></strong> option in the router configuration, which is off by default:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">export</span> <span class="token keyword">const</span> appConfig<span class="token operator">:</span> ApplicationConfig <span class="token operator">=</span> <span class="token punctuation">{</span>
    providers<span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token function">provideRouter</span><span class="token punctuation">(</span>
        routes<span class="token punctuation">,</span>
        <span class="token function">withComponentInputBinding</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        <span class="token function">withRouterResources</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">)</span>
    <span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Notice also the use of the optional <code>withRouterResources()</code>. This is another signal-based feature of the router that is off by default. It provides a signal-based alternative to resolvers.</p>
<p>The contents of the routes file follow the same format as usual.</p>
<p>For this guide, let's use a course edit route with a path parameter and a route resource.</p>
<p>The course resource is responsible for loading a course from the backend, based on the content of the url:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">export</span> <span class="token keyword">const</span> routes<span class="token operator">:</span> Routes <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">'courses/edit-course/:courseUrl'</span><span class="token punctuation">,</span>
    <span class="token function-variable function">loadComponent</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">'./course-edit/course-edit.component'</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>m <span class="token operator">=></span> m<span class="token punctuation">.</span>CourseEditComponent<span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token function-variable function">resources</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">{</span> params <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token punctuation">{</span>
      course<span class="token operator">:</span> <span class="token generic-function"><span class="token function">httpResource</span><span class="token generic class-name"><span class="token operator">&lt;</span>Course<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span>
        <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">/api/courses/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token function">params</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token string">'courseUrl'</span><span class="token punctuation">]</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
      <span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The component is lazy-loaded, and the router waits for the course resource to load before displaying the page.</p>
<p>We still render the component through a normal outlet as usual:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>main</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>app-main<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>router-outlet</span> <span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>main</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>Let's use this URL throughout the examples:</p>
<div class="code-block"><span class="code-lang">text</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">/courses/edit-course/angular-router-course?mode=edit&amp;couponCode=NEW_YEAR
</code></pre></div>
<p>It gives us a path parameter, two query parameters, and a resolved course. Let's see how all of them reach our component as signals.</p>
<h2 id="path-parameters-as-signal-inputs">Path parameters as signal inputs</h2>
<p>To receive the <code>:courseUrl</code> path parameter, we declare an input with the same name in <code>CourseEditComponent</code>:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CourseEditComponent</span> <span class="token punctuation">{</span>
  <span class="token keyword">readonly</span> courseUrl <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>And that's it!</p>
<p>With component input binding enabled, the router supplies the URL segment <code>angular-router-course</code> to this input.</p>
<p>It all happens purely through a naming convention: the name of the component input <code>courseUrl</code> matches the name of the path variable <code>:courseUrl</code> in the route configuration.</p>
<p>We read this input and use it like any other signal-based input.</p>
<p>It really is just a plain component input; there is nothing special about it:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>Course URL: {{ courseUrl() }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>Notice that, unlike when using older router APIs, we didn't need to inject <code>ActivatedRoute</code>, subscribe to <code>paramMap</code>, or copy the value into a local field.</p>
<p><strong>The input name establishes the connection.</strong></p>
<p>The input is required because this route always includes <code>:courseUrl</code>.</p>
<p>That declaration expresses the component's expectation; it does not validate the URL or check whether the course exists.</p>
<h2 id="query-parameters-as-signal-inputs">Query parameters as signal inputs</h2>
<p>Query parameters can also be injected into the component using exactly the same signal-based naming convention:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CourseEditComponent</span> <span class="token punctuation">{</span>
  <span class="token keyword">readonly</span> mode <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token string">'edit'</span> <span class="token operator">|</span> <span class="token string">'create'</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">readonly</span> couponCode <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>For our example URL, <code>mode()</code> returns <code>edit</code> and <code>couponCode()</code> returns <code>NEW_YEAR</code>.</p>
<p>Notice that we don't declare query parameters in the route's <code>path</code>.</p>
<p>The router matches their names directly to the component inputs.</p>
<p>These inputs are <em>optional</em> because the page can be opened without either query parameter.</p>
<p>We can account for that in the template:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@if (couponCode(); as coupon) {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>Coupon applied: {{ coupon }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span>
}
</code></pre></div>
<p>Notice that input signals are <strong>read-only</strong>.</p>
<p>If a query parameter changes in the URL, the corresponding input signal will emit a new value.</p>
<h2 id="route-resources-data-as-signal-inputs">Route resources data as signal inputs</h2>
<p>Route resources load data before the router displays a component.</p>
<p>We can receive that data through signal inputs too, using the same naming convention.</p>
<p>Our route configuration already registers a a route resource:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token function-variable function">resources</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">{</span> params <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token punctuation">{</span>
    course<span class="token operator">:</span> <span class="token generic-function"><span class="token function">httpResource</span><span class="token generic class-name"><span class="token operator">&lt;</span>Course<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span>
      <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">/api/courses/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token function">params</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token string">'courseUrl'</span><span class="token punctuation">]</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
    <span class="token punctuation">)</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div>
<p>To receive the output of this route resource, we declare a component input named <strong><code>course</code></strong>:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CourseEditComponent</span> <span class="token punctuation">{</span>
  <span class="token keyword">readonly</span> course <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Course<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The component receives the result through <code>course()</code> and can render it directly:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>{{ course().description }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>So, as you can see, everything happens through naming conventions!</p>
<h2 id="angular-router-in-depth-course">Angular Router In Depth Course</h2>
<p>If you are enjoying the teaching style in this article, check out the free sample video lessons available as part of the <a href="https://angular-university.io/course/angular-router-in-depth-course" target="_blank" rel="noopener">Angular Router In Depth course</a>:</p>
<p><a href="https://angular-university.io/course/angular-router-in-depth-course" target="_blank" rel="noopener"><img src="https://d3vigmphadbn9b.cloudfront.net/course-images/large-images/angular-router-in-depth.jpg" alt="Angular Router In Depth course" loading="lazy" decoding="async"></a></p>
<p>And now, back to the article.</p>
<h2 id="active-navigation-with-isactive">Active navigation with isActive</h2>
<p>The standalone <a href="https://angular.dev/api/router/isActive" target="_blank" rel="noopener"><code>isActive(url, router)</code> function</a> returns a <code>Signal&lt;boolean&gt;</code>. It tells us whether the given URL is active and updates automatically as the route changes.</p>
<p>By default, matching <strong>includes child paths</strong>, so <code>/courses/edit-course</code> also matches <code>/courses/edit-course/angular-router-course</code>.</p>
<p>Here is how we use it:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> <span class="token keyword">readonly</span> router <span class="token operator">=</span> <span class="token function">inject</span><span class="token punctuation">(</span>Router<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">protected</span> <span class="token keyword">readonly</span> editingCourse <span class="token operator">=</span> <span class="token function">isActive</span><span class="token punctuation">(</span>
    <span class="token string">'/courses/edit-course'</span><span class="token punctuation">,</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>router
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We can read the signal directly in a class binding:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">routerLink</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/<span class="token punctuation">"</span></span> <span class="token attr-name">[class.editing]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>editingCourse()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  Angular Router In Depth
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span>
</code></pre></div>
<h2 id="navigation-status-with-the-signal-based-api-currentnavigation">Navigation status with the signal-based API currentNavigation()</h2>
<p>The Router's <a href="https://angular.dev/api/router/Router#currentNavigation" target="_blank" rel="noopener"><code>currentNavigation</code></a> is a <code>Signal&lt;Navigation | null&gt;</code>. It holds the navigation <strong>in progress right now</strong> and goes back to <code>null</code> once that navigation succeeds, fails, or is cancelled and the router becomes idle.</p>
<p>Calling <code>router.currentNavigation()</code> reads the current <code>Navigation</code> object, or <code>null</code> if no navigation is running.</p>
<p>For example, when we click a course link, the object is available while the router processes the navigation, including waiting for the course data to load via the route resource.</p>
<p>The <a href="https://angular.dev/api/router/Navigation" target="_blank" rel="noopener"><code>Navigation</code> object</a> describes a navigation operation. Its most useful properties include:</p>
<ul>
<li><code>id</code>: the unique identifier of this navigation.</li>
<li><code>initialUrl</code>: the requested destination before redirects, represented as a <code>UrlTree</code>.</li>
<li><code>finalUrl</code>: the destination after redirects, also a <code>UrlTree</code>. This can be <code>undefined</code> early in navigation.</li>
<li><code>trigger</code>: how navigation started: <code>imperative</code> for an application navigation, <code>popstate</code> for a browser history event, or <code>hashchange</code> for a hash-change event.</li>
<li><code>extras</code>: the navigation options, such as <code>replaceUrl</code>, <code>skipLocationChange</code>, or custom <code>state</code>.</li>
<li><code>previousNavigation</code>: the previous successful navigation, or <code>null</code> if there wasn't one.</li>
</ul>
<p>The URL properties contain Angular <code>UrlTree</code> objects. Use <code>router.serializeUrl()</code> when you need their string representation. Also, <code>finalUrl</code> is only guaranteed to be available after routes have been recognized.</p>
<p>So we can inspect the navigation details or simply check whether the value is non-null to know that navigation is in progress.</p>
<p>In the application component, we can derive a loading flag:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

  <span class="token keyword">private</span> <span class="token keyword">readonly</span> router <span class="token operator">=</span> <span class="token function">inject</span><span class="token punctuation">(</span>Router<span class="token punctuation">)</span><span class="token punctuation">;</span>
  
  <span class="token keyword">protected</span> <span class="token keyword">readonly</span> navigating <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span><span class="token function">currentNavigation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!==</span> <span class="token keyword">null</span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Then display an indicator alongside the outlet:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@if (navigating()) {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span> <span class="token attr-name">role</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>status<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Loading page...<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span>
}

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>router-outlet</span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>This provides feedback while our course resolver is loading, before the target component appears.</p>
<p>The flag follows the router's state automatically.</p>
<p><code>Router.events</code> remains available when we need individual event details, but a basic navigation indicator can use this signal directly.</p>
<h2 id="tracking-the-last-successful-navigation">Tracking the last successful navigation</h2>
<p>The Router's <a href="https://angular.dev/api/router/Router#lastSuccessfulNavigation" target="_blank" rel="noopener"><code>lastSuccessfulNavigation</code></a> is a <code>Signal&lt;Navigation | null&gt;</code>. It holds the most recent navigation that <em>completed successfully</em>, or <code>null</code> if no navigation has succeeded yet.</p>
<p>Calling <code>router.lastSuccessfulNavigation()</code> reads that object. It has the same <code>Navigation</code> properties described above, and a later failed or cancelled navigation does not replace it.</p>
<p>For example, we can derive its final URL:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

   <span class="token keyword">private</span> <span class="token keyword">readonly</span> router <span class="token operator">=</span> <span class="token function">inject</span><span class="token punctuation">(</span>Router<span class="token punctuation">)</span><span class="token punctuation">;</span>
   
  <span class="token keyword">protected</span> <span class="token keyword">readonly</span> lastSuccessfulUrl <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> navigation <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span><span class="token function">lastSuccessfulNavigation</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> url <span class="token operator">=</span> navigation<span class="token operator">?.</span>finalUrl<span class="token punctuation">;</span>

    <span class="token keyword">return</span> url <span class="token operator">?</span> <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span><span class="token function">serializeUrl</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This value remains available when the router becomes idle. It describes the latest completed success, while <code>currentNavigation()</code> describes work in progress.</p>
<h2 id="conclusions-and-key-takeaways">Conclusions and Key Takeaways</h2>
<p>As you can see, much of the Angular Router's integration with signals comes down to <strong>input binding and naming conventions</strong>. Unless you enable <code>withComponentInputBinding()</code>, this integration is easy to miss!</p>
<p>Once you adopt the signals approach, everyday routing becomes much more straightforward. Parameters and resolved data arrive as component inputs, and your component reacts to them using the signal APIs you already know.</p>
<p>For these common tasks, you no longer need to subscribe to the Router's Observable-based APIs.</p>
<p>Let me know in the comments below if you have any questions. I'll be happy to help!</p>
<p>I hope you found this article helpful. <strong>Subscribe to my newsletter</strong> if you want me to send my next article straight to your inbox:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
]]></content:encoded>
    </item>
    <item>
      <title>Testing Angular Services with HttpTestingController  (Complete Guide)</title>
      <link>https://blog.angular-university.io/angular-http-testing-httptestingcontroller/</link>
      <guid isPermaLink="false">69e0df85042fb900015e68a5</guid>
      <pubDate>Thu, 16 Apr 2026 13:15:12 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Testing</category>
      <description>A complete guide for testing HTTP-based services the Angular way by using HttpTestingController.
Common pitfalls will be explained.</description>
      <content:encoded><![CDATA[<p>The service layer of most Angular applications is HTTP-based. For testing such services, doing real HTTP calls in a test scenario would prove to be <strong>tricky, slow, and hard to maintain</strong>.</p>
<p>Going that route would involve spinning a real HTTP test server, which would immediately turn service layer tests into full-blown integration tests, rather than the simple unit tests they should be.</p>
<p>Mocking HTTP requests by patching browser APIs directly (e.g. overriding<br>
<code>XMLHttpRequest</code> or <code>fetch</code>) is another way of doing it, but it is fragile and Angular already gives you a much better solution out of the box.</p>
<p>To solve this problem, Angular provides a <strong>built-in, batteries-included solution for testing HTTP services</strong> — <code>HttpTestingController</code>.</p>
<p>In this guide we will walk you through everything you need to know to use this test utility to write clean, reliable, and fast unit tests for all your HTTP-based services.</p>
<blockquote>
<p>Notice that all code will be using the new Vitest syntax, and not Jasmine.</p>
</blockquote>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post will cover the following topics:</p>
<ul>
<li>What is Angular HTTP Mocking and why it matters</li>
<li>Example of an Angular HTTP Service to Test</li>
<li>Setting Up HTTP Testing with provideHttpClientTesting</li>
<li>Using verify() to Avoid Unexpected HTTP Requests</li>
<li>Your First Angular HTTP Mock Test</li>
<li>Asserting HTTP Requests with predicates instead of Urls</li>
<li>Testing Error Handling in HTTP Scenarios (regular vs network errors)</li>
<li>Mocking HTTP PUT and Other Mutating Requests</li>
<li>Conclusions and Key Takeaways</li>
</ul>
<p>So without further ado, let's get started with our Angular HTTP Mocking deep dive.</p>
<h2 id="what-is-angular-http-mocking-and-why-it-matters">What is Angular HTTP Mocking and why it matters</h2>
<p>When you write a unit test for an Angular HTTP-based service, you <strong>don't</strong> want any real network traffic <em>at all</em>.</p>
<p>Instead, you want to:</p>
<ul>
<li><strong>Control the HTTP response</strong> — return manually from inside the test whatever data the test needs</li>
<li><strong>Control timing</strong> — resolve responses <em>synchronously</em> from within the test programmatically</li>
<li><strong>Assert the request itself</strong> — verify that your service constructed the HTTP request correctly: correct URL, method, headers and body</li>
<li><strong>Avoid unexpected requests</strong> — confirm no unexpected HTTP requests slipped through</li>
</ul>
<p>Angular's <code>HttpTestingController</code> gives you all of that and more.</p>
<p>It works by replacing the real HTTP backend (the one that actually talks to the network) with an in-memory &quot;backend&quot; that intercepts requests and lets you respond to them manually from within your test.</p>
<p>The key insight is: <code>HttpTestingController</code> does <em>not</em> mock <code>HttpClient</code>, at all!</p>
<p>Instead, it <strong>replaces the transport layer underneath it</strong>.</p>
<p>Your service code runs exactly as it would in production — it calls <code>HttpClient</code> methods, uses <code>HttpParams</code>, processes responses — but no network requests are made.</p>
<p>Notice the following caveat:</p>
<blockquote>
<p>You can only benefit from <code>HttpTestingController</code> if you build your services around <code>HttpClient</code>.</p>
</blockquote>
<p>That alone is already a good reason to use <code>HttpClient</code> instead of something like <code>fetch()</code>.</p>
<p>Also worth mentioning:</p>
<blockquote>
<p>Worried that <code>HttpClient</code> is Observable-based and you don't want to use Observables? We will show how to handle that too.</p>
</blockquote>
<hr>
<h2 id="example-of-an-angular-http-service-to-test">Example of an Angular HTTP Service to Test</h2>
<p>Here is the service about which we will build our test suite around.</p>
<p>It covers some of the most common HTTP patterns you'll ever encounter in practice:</p>
<ul>
<li>a GET by id</li>
<li>a PUT (save)</li>
<li>and a GET with multiple query parameters</li>
</ul>
<p>Here is the Angular HTTP service that we will be testing:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Injectable</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  providedIn<span class="token operator">:</span> <span class="token string">'root'</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CoursesService</span> <span class="token punctuation">{</span>

  <span class="token keyword">private</span> http <span class="token operator">=</span> <span class="token function">inject</span><span class="token punctuation">(</span>HttpClient<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">async</span> <span class="token function">findCourseById</span><span class="token punctuation">(</span>
  courseId<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>Course<span class="token operator">></span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">firstValueFrom</span><span class="token punctuation">(</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>http<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">get</span><span class="token generic class-name"><span class="token operator">&lt;</span>Course<span class="token operator">></span></span></span><span class="token punctuation">(</span>
      <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">/api/courses/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>courseId<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">async</span> <span class="token function">saveCourse</span><span class="token punctuation">(</span>courseId<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">,</span> 
  changes<span class="token operator">:</span> Partial<span class="token operator">&lt;</span>Course<span class="token operator">></span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>Course<span class="token operator">></span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">firstValueFrom</span><span class="token punctuation">(</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>http<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">put</span><span class="token generic class-name"><span class="token operator">&lt;</span>Course<span class="token operator">></span></span></span><span class="token punctuation">(</span>
      <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">/api/courses/</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>courseId<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span> 
      changes<span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">async</span> <span class="token function">findLessons</span><span class="token punctuation">(</span>
    courseId<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">,</span>
    filter <span class="token operator">=</span> <span class="token string">''</span><span class="token punctuation">,</span>
    sortOrder <span class="token operator">=</span> <span class="token string">'asc'</span><span class="token punctuation">,</span>
    pageNumber <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span>
    pageSize <span class="token operator">=</span> <span class="token number">3</span>
  <span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>Lesson<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> params <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HttpParams</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'courseId'</span><span class="token punctuation">,</span> courseId<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'filter'</span><span class="token punctuation">,</span> filter<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'sortOrder'</span><span class="token punctuation">,</span> sortOrder<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'pageNumber'</span><span class="token punctuation">,</span> pageNumber<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token string">'pageSize'</span><span class="token punctuation">,</span> pageSize<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> res <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token function">firstValueFrom</span><span class="token punctuation">(</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>http<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">get</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token punctuation">{</span> 
      payload<span class="token operator">:</span> Lesson<span class="token punctuation">[</span><span class="token punctuation">]</span> 
      <span class="token punctuation">}</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">/api/lessons</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span> <span class="token punctuation">{</span> params <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span>payload<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>A few things to note about this HTTP service before we start testing it:</p>
<ul>
<li>it uses <code>HttpClient</code>, which is the pre-requisite for using <code>HttpTestingController</code></li>
<li><code>HttpClient</code> is Observable-based, but we want our service layer to be Promise-based and compatible with the async/await syntax which makes async development super convenient, almost synchronous-like.</li>
<li>To convert Observables to Promises, we are using <code>firstValueFrom()</code> which is a standard Angular RxJs interop utility</li>
<li>The use of <code>HttpClient</code> is well justified even if we don't use Observables, for two main reasons: the ability to easily mock Http requests in tests and the ability to use Angular Http interceptors</li>
<li>everything else in this article regarding the use of <code>HttpTestingController</code> is independent of the API of the service layer: Promises or Observables both work well, as long as our service internally uses <code>HttpClient</code></li>
</ul>
<h2 id="setting-up-http-testing-with-providehttpclienttesting">Setting Up HTTP Testing with provideHttpClientTesting</h2>
<p>To test the <code>CoursesService</code>, let's go ahead and let's set up a test suite for it:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">describe</span><span class="token punctuation">(</span><span class="token string">'CoursesService'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> service<span class="token operator">:</span> CoursesService<span class="token punctuation">;</span>
  <span class="token keyword">let</span> httpTesting<span class="token operator">:</span> HttpTestingController<span class="token punctuation">;</span>

  <span class="token function">beforeEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    TestBed<span class="token punctuation">.</span><span class="token function">configureTestingModule</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      providers<span class="token operator">:</span> <span class="token punctuation">[</span>
        <span class="token function">provideHttpClient</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        <span class="token function">provideHttpClientTesting</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">]</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    service <span class="token operator">=</span> TestBed<span class="token punctuation">.</span><span class="token function">inject</span><span class="token punctuation">(</span>CoursesService<span class="token punctuation">)</span><span class="token punctuation">;</span>
    httpTesting <span class="token operator">=</span> TestBed<span class="token punctuation">.</span><span class="token function">inject</span><span class="token punctuation">(</span>HttpTestingController<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">afterEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    httpTesting<span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Let's break down what we just did here:</p>
<ul>
<li>we are setting up a mini Angular runtime environment before each test, that only contains an instance of <code>CoursesService</code> and it's direct dependencies</li>
<li>notice that we are providing an actual instance of <code>HttpClient</code> via <code>provideHttpClient()</code>. We are <strong>not</strong> mocking it.</li>
<li>But then on top of it, we are then calling <code>provideHttpClientTesting()</code>. What this does that it replaces the default <code>XMLHttpRequest</code> transport layer used by <code>HttpClient</code> with a mock-based implementation</li>
</ul>
<p>So that's it for our test suite setup.</p>
<p>But what about that funny-looking <code>verify()</code> call, what's up with that?</p>
<h2 id="using-verify-to-avoid-unexpected-http-requests">Using verify() to Avoid Unexpected HTTP Requests</h2>
<p>Regarding the <code>afterEach</code> block in our test suite:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">afterEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  httpTesting<span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>This call to <code>verify()</code> checks that no HTTP requests were made during the test that went totally unhandled and unaccounted for in our tests.</p>
<p>As you will see, during our HTTP tests one of the main things that we will do is to use <code>HttpTestingController</code> to <em>assert</em> that certain HTTP requests were made, with a given url, body, params, headers, etc.</p>
<p>If at the end of the test, certain requests remain unchecked, that could be the sign of a bug.</p>
<p>Consider this scenario: a service method accidentally calls two endpoints instead of one (due to a bug).</p>
<p>Without <code>verify()</code>, your test passes as long as the request you care about is found. But that extra unintended request would still be made.</p>
<p>So the bug would <strong>not</strong> get caught.</p>
<p>With <code>verify()</code> on the other hand, the extra accidental request gets caught and the test will fail.</p>
<blockquote>
<p>Always put <code>verify()</code> in <code>afterEach</code>, not inside individual tests. This way you can't accidentally forget it on a single test.</p>
</blockquote>
<h2 id="your-first-angular-http-mock-test">Your First Angular HTTP Mock Test</h2>
<p>Let's start by testing <code>findCourseById</code>, which is a plain HTTP GET request.</p>
<p>Assume the following mock data is used:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">const</span> <span class="token constant">MOCK_COURSE</span><span class="token operator">:</span> Course <span class="token operator">=</span> <span class="token punctuation">{</span>
    id<span class="token operator">:</span> <span class="token number">12</span><span class="token punctuation">,</span>
    title<span class="token operator">:</span> <span class="token string">'Angular For Beginners'</span><span class="token punctuation">,</span>
    description<span class="token operator">:</span> <span class="token string">'Learn Angular from scratch.'</span><span class="token punctuation">,</span>
    iconUrl<span class="token operator">:</span> <span class="token string">'https://example.com/icon.png'</span><span class="token punctuation">,</span>
    category<span class="token operator">:</span> <span class="token string">'BEGINNER'</span><span class="token punctuation">,</span>
    lessonsCount<span class="token operator">:</span> <span class="token number">10</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Here is the complete test with some comments, and then we'll break it down line by line:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'should retrieve a course by id'</span><span class="token punctuation">,</span> <span class="token keyword">async</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    
  <span class="token comment">// 1. Trigger the HTTP request</span>
  <span class="token comment">// do NOT "await" yet, as that would hang </span>
  <span class="token comment">// and timeout the test</span>
  <span class="token keyword">const</span> coursePromise <span class="token operator">=</span> service<span class="token punctuation">.</span><span class="token function">findCourseById</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 2. Assert that exactly one request</span>
  <span class="token comment">// was made to this exact URL</span>
  <span class="token keyword">const</span> req <span class="token operator">=</span> httpTesting<span class="token punctuation">.</span><span class="token function">expectOne</span><span class="token punctuation">(</span><span class="token string">'/api/courses/12'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 3. Assert request method</span>
  <span class="token function">expect</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'GET'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 4. Trigger response to GET with mock data</span>
  req<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span><span class="token constant">MOCK_COURSE</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 5. Only now await the resolved value</span>
  <span class="token keyword">const</span> course <span class="token operator">=</span> <span class="token keyword">await</span> coursePromise<span class="token punctuation">;</span>

  <span class="token function">expect</span><span class="token punctuation">(</span>course<span class="token punctuation">.</span>id<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token function">expect</span><span class="token punctuation">(</span>course<span class="token punctuation">.</span>title<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'Angular For Beginners'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Let's now break this down line by line:</p>
<p><strong>Step 1 — launch the request without <code>await</code>.</strong> <code>service.findCourseById(12)</code> triggers the HTTP call and returns a pending Promise.</p>
<p>The request is now sitting in the testing controller's queue, waiting to be validated and flushed.</p>
<p>If you <code>await</code> here, the test would hang forever, as the returned Promise can only resolve after we provide a mock value for the HTTP calls.</p>
<p>And we can only do that if the code execution continues <em>after</em> calling the service, as we will see.</p>
<p><strong>Step 2 — <code>expectOne</code></strong> locates the pending request by URL and confirms that exactly one such request exists, with that specific url.</p>
<p>If zero or more than one request matches, the test throws immediately. So this instruction also acts as a test assertion.</p>
<p><strong>Step 3 — <code>req.request</code></strong> lets you inspect the outgoing request <em>before</em> providing a response. Here we assert it is indeed a <code>GET</code>.</p>
<p><strong>Step 4 — <code>flush</code></strong> provides the response body. The testing backend resolves the Observable, <code>firstValueFrom</code> resolves the Promise.</p>
<p><strong>Step 5</strong> - is now safe to <code>await</code> because the response has already been provided. The Promise is already resolved, so <code>await</code> returns immediately with the course value.</p>
<p>If we had called <code>await</code> on that promise at any moment before flush, the test would have hung.</p>
<h2 id="asserting-http-requests-with-predicates-instead-of-urls">Asserting HTTP Requests with predicates instead of Urls</h2>
<p>As an alternative, <code>expectOne</code> we also take a filter function to match a request in a more flexible way, instead of just a plain string.</p>
<p>Let's test the <code>findLessons()</code> method, and use <code>expectOne</code> with a filter function:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'should find lessons by query'</span><span class="token punctuation">,</span> <span class="token keyword">async</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

    <span class="token keyword">const</span> promise <span class="token operator">=</span> service<span class="token punctuation">.</span><span class="token function">findLessons</span><span class="token punctuation">(</span>
    <span class="token number">12</span><span class="token punctuation">,</span> <span class="token string">'filter-text'</span><span class="token punctuation">,</span> <span class="token string">'desc'</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> req <span class="token operator">=</span> httpTesting<span class="token punctuation">.</span><span class="token function">expectOne</span><span class="token punctuation">(</span>
        req <span class="token operator">=></span> req<span class="token punctuation">.</span>url <span class="token operator">===</span> <span class="token string">'/api/lessons'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> params <span class="token operator">=</span> req<span class="token punctuation">.</span>request<span class="token punctuation">.</span>params<span class="token punctuation">;</span>
    
    <span class="token function">expect</span><span class="token punctuation">(</span>params<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'courseId'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'12'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>params<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'filter'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'filter-text'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>params<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'sortOrder'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'desc'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>params<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'pageNumber'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'2'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>params<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'pageSize'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'10'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> mockLessons <span class="token operator">=</span> <span class="token punctuation">{</span>
    payload<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">{</span>
           id<span class="token operator">:</span> <span class="token number">12</span><span class="token punctuation">,</span> 
           description<span class="token operator">:</span> <span class="token string">"Lesson 1"</span>
        <span class="token punctuation">}</span><span class="token punctuation">]</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    
    req<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span>mockLessons<span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token keyword">await</span> promise<span class="token punctuation">;</span>
    
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span>mockLessons<span class="token punctuation">.</span>payload<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div>
<p>This filter function comes in especially handy in situations such as this one, when the full url is complex due to the presence of query parameters.</p>
<p>Notice that besides filtering on the url, we can also filter on the request headers and body as well.</p>
<p>Let's now talk about testing different types of error scenarios.</p>
<h2 id="angular-testing-in-depth-course">Angular Testing In Depth Course</h2>
<p>If you are enjoying the teaching style in this article, check out the free sample video lessons available as part of the <a href="https://angular-university.io/course/angular-testing-in-depth" target="_blank" rel="noopener">Angular Testing In Depth (Signals Edition)</a> course:</p>
<p><a href="https://angular-university.io/course/angular-testing-in-depth" target="_blank" rel="noopener"><img src="https://d3vigmphadbn9b.cloudfront.net/course-images/large-images/angular-testing-In-depth.jpg" alt="" loading="lazy" decoding="async"></a></p>
<p>And now, back to the article.</p>
<h2 id="testing-error-handling-in-http-scenarios">Testing Error Handling in HTTP Scenarios</h2>
<p>We can also use the <code>HttpTestingController</code> to simulate error responses, by explicitly setting an error status code.</p>
<p>Here is how we can simulate a typical 404 Not Found scenario:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">
<span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'should reject if the server returns 404'</span><span class="token punctuation">,</span> <span class="token keyword">async</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> coursePromise <span class="token operator">=</span> service<span class="token punctuation">.</span><span class="token function">findCourseById</span><span class="token punctuation">(</span><span class="token number">999</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> req <span class="token operator">=</span> httpTesting<span class="token punctuation">.</span><span class="token function">expectOne</span><span class="token punctuation">(</span>
        <span class="token string">'/api/courses/999'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    req<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span><span class="token string">'Course not found'</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
      status<span class="token operator">:</span> <span class="token number">404</span><span class="token punctuation">,</span>
      statusText<span class="token operator">:</span> <span class="token string">'Not Found'</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> <span class="token function">expect</span><span class="token punctuation">(</span>coursePromise<span class="token punctuation">)</span><span class="token punctuation">.</span>rejects<span class="token punctuation">.</span><span class="token function">toThrow</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Notice that this last test simulates a scenario when the server actually provided a response.</p>
<p>It's also possible to simulate other more critical scenarios like network failure:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'should handle network error '</span><span class="token punctuation">,</span> <span class="token keyword">async</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    
    <span class="token keyword">const</span> coursePromise <span class="token operator">=</span> service<span class="token punctuation">.</span><span class="token function">findCourseById</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> req <span class="token operator">=</span> httpTesting<span class="token punctuation">.</span><span class="token function">expectOne</span><span class="token punctuation">(</span><span class="token string">'/api/courses/1'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    req<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ProgressEvent</span><span class="token punctuation">(</span><span class="token string">'network error'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> <span class="token function">expect</span><span class="token punctuation">(</span>coursePromise<span class="token punctuation">)</span><span class="token punctuation">.</span>rejects<span class="token punctuation">.</span><span class="token function">toThrow</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div>
<p>Notice that <code>req.error()</code> takes a <code>ProgressEvent</code> — the same low-level browser event that <code>XMLHttpRequest</code> fires when a connection drops, DNS fails, or a CORS preflight is rejected.</p>
<p>There is no HTTP response involved at all: the request simply never completes.</p>
<h2 id="mocking-http-put-and-other-mutating-requests">Mocking HTTP PUT and Other Mutating Requests</h2>
<p>For testing PUT requests, the exact same logic applies as before.</p>
<p>The only difference is the method of the HTTP request, but the overall test strategy is the same.</p>
<p>For completeness, here is how to test the <code>saveCourse()</code> method:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">describe</span><span class="token punctuation">(</span><span class="token string">'saveCourse'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

  <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">'should save the course changes'</span><span class="token punctuation">,</span> <span class="token keyword">async</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> changes<span class="token operator">:</span> Partial<span class="token operator">&lt;</span>Course<span class="token operator">></span> <span class="token operator">=</span> <span class="token punctuation">{</span> 
        title<span class="token operator">:</span> <span class="token string">'Angular Advanced Course'</span> 
    <span class="token punctuation">}</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> savePromise <span class="token operator">=</span> service<span class="token punctuation">.</span><span class="token function">saveCourse</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">,</span> changes<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> req <span class="token operator">=</span> httpTesting<span class="token punctuation">.</span><span class="token function">expectOne</span><span class="token punctuation">(</span>
       <span class="token string">'/api/courses/12'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">expect</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'PUT'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>request<span class="token punctuation">.</span>body<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span>changes<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> updatedCourse<span class="token operator">:</span> Course <span class="token operator">=</span> <span class="token punctuation">{</span>
      id<span class="token operator">:</span> <span class="token number">12</span><span class="token punctuation">,</span>
      title<span class="token operator">:</span> <span class="token string">'Angular Advanced Course'</span><span class="token punctuation">,</span>
      description<span class="token operator">:</span> <span class="token string">'Advanced Angular patterns.'</span><span class="token punctuation">,</span>
      iconUrl<span class="token operator">:</span> <span class="token string">'https://example.com/icon.png'</span><span class="token punctuation">,</span>
      category<span class="token operator">:</span> <span class="token string">'ADVANCED'</span><span class="token punctuation">,</span>
      lessonsCount<span class="token operator">:</span> <span class="token number">20</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>

    req<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span>updatedCourse<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">const</span> saved <span class="token operator">=</span> <span class="token keyword">await</span> savePromise<span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>saved<span class="token punctuation">.</span>title<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'Angular Advanced Course'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>And with this, we have completed testing all the methods of <code>CoursesService</code>.</p>
<p>Let's now wrap everything up, and highlight some of the key concepts we have learned.</p>
<h2 id="conclusions-and-key-takeaways">Conclusions and Key Takeaways</h2>
<p><code>HttpTestingController</code> gives you a clean, Angular-native way to test HTTP services without spinning up a real server or patching browser globals.</p>
<p>It makes it even more compelling to keep using the Angular <code>HttpClient</code> service in your services, even if you are not using Observable-based service layers.</p>
<p>Here is what to remember:</p>
<p><strong>The golden rule:</strong> never <code>await</code> a service call before calling <code>flush</code>. The correct sequence is: <em>call → expectOne → flush → await</em>.</p>
<p><strong>Always call <code>verify()</code> in <code>afterEach</code>.</strong> It is your safety net against unintended requests that would otherwise go unnoticed.</p>
<p><strong>Use a filter function with <code>expectOne</code> when needed.</strong> there are sometimes more convenient ways to locate a request that don't involve knowing the full URL used.</p>
<p><strong><code>flush</code> simulates any HTTP response</strong> — success, but also error responses like 4xx, 5xx. Use <code>error()</code> for network-level failures.</p>
<p>With these patterns in place, your service layer tests will be fast, deterministic, maintainable and genuinely useful.</p>
<p>I hope you found this article helpful. Subscribe to my newsletter if you want me to send you my next article to your mailbox:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
]]></content:encoded>
    </item>
    <item>
      <title>Modern Angular Testing with Vitest: The Fundamentals</title>
      <link>https://blog.angular-university.io/angular-testing-vitest/</link>
      <guid isPermaLink="false">69a0576adbf5e000013edca2</guid>
      <pubDate>Thu, 26 Feb 2026 15:58:56 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Testing</category>
      <description>In this article, you’ll learn the fundamentals of Vitest: the new way of testing in Angular. If you’re familiar with Karma and Jasmine, we’ll start with a comparison to help you quickly understand what’s changed.</description>
      <content:encoded><![CDATA[<p>For many years, Angular developers relied on the Karma/Jasmine tool stack, which came bundled with the Angular CLI.</p>
<p>While <strong>alternatives such as Jest</strong> were sometimes used, Karma and Jasmine remained the default and most widely adopted solution.</p>
<p>Karma acted as the test runner, executing tests in a real browser environment. Jasmine served as the testing framework, providing the APIs needed to define test suites, specifications, and assertions.</p>
<blockquote>
<p>The Angular CLI no longer uses Karma/Jasmine for new projects.</p>
</blockquote>
<p>They can still be used if needed, but the new default testing solution is now Vitest — a <strong>modern, fast, all-in-one</strong>, batteries-included testing framework that provides an integrated solution for almost every aspect of testing.</p>
<p>This article introduces the fundamental concepts of Vitest, helping you understand the new capabilities available when writing Angular tests.</p>
<p>We will explore key concepts such as spying, mocking, and pure mocks. You will also learn how to ensure proper test isolation by understanding the differences between clearing, resetting, and restoring mocks.</p>
<p>This post focuses strictly on Vitest fundamentals.</p>
<p>It does not cover the setup and configuration of Angular tests, component testing strategies, or other Angular-specific testing patterns — those topics will be addressed in future articles.</p>
<p>If you are already familiar with Karma and Jasmine, we will begin by comparing the Karma/Jasmine tool stack with Vitest to help you quickly understand the key differences.</p>
<h1 id="table-of-contents">Table of Contents</h1>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>Introduction to Vitest: comparison with Karma / Jasmine.</li>
<li>How Spying works in Vitest: understanding Vitest spies</li>
<li>How Mocking works in Vitest</li>
<li>Pure mocks in Vitest</li>
<li>Mock clearing - understanding mockClear()</li>
<li>Mock resetting - understanding mockReset()</li>
<li>Mock restoring - understanding mockRestore()</li>
<li>Configuring Vitest to clean up between tests</li>
<li>Conclusions</li>
</ul>
<p>So without further ado, let's get started with this deep dive into the fundamentals of Vitest!</p>
<h2 id="introduction-to-vitest-comparison-with-karma-jasmine">Introduction to Vitest: comparison with Karma/Jasmine</h2>
<p>With Vitest, the test runner is not a separate tool like Karma — it is built directly into Vitest itself. This eliminates the need to coordinate multiple tools and provides a more integrated testing experience.</p>
<p>Vitest is <strong>significantly faster</strong> than Karma in most scenarios.</p>
<p>One key reason for the extra speed is that Vitest <strong>does not require launching and managing a full browser</strong> instance by default.</p>
<p>Instead, tests typically run in a simulated browser environment powered by a lightweight, non-visual DOM implementation such as <a href="https://github.com/jsdom/jsdom" target="_blank" rel="noopener">jsdom</a>.</p>
<p>Although jsdom is the default DOM environment, Vitest gives you full control over the execution environment. For example, you can replace jsdom with other lightweight DOM implementations such as <a href="https://github.com/capricorn86/happy-dom" target="_blank" rel="noopener">happy-dom</a>.</p>
<p>If needed, Vitest can also run tests in a real browser using its browser mode (powered by tools like Playwright), allowing execution in environments such as Chromium. This provides flexibility when true browser APIs or rendering behavior must be tested.</p>
<p>In most cases, however, the default jsdom-based configuration is more than sufficient and offers excellent performance.</p>
<p>And so that covers how the Vitest test runner differs from Karma.</p>
<p>But what about writing tests themselves? How does the Vitest API compare to Jasmine?</p>
<h3 id="the-vitest-testing-api">The Vitest testing API</h3>
<p>At first glance, the Vitest testing API looks very similar to Jasmine. It follows the familiar <code>describe</code> / <code>it</code> / <code>expect</code> structure for organizing test suites and writing assertions.</p>
<p>There are, however, a few important differences:</p>
<ul>
<li><strong>More powerful assertions</strong> – Vitest’s assertion system is inspired and comparable in expressiveness to <a href="https://jestjs.io/" target="_blank" rel="noopener">Jest</a>, which is a popular alternative to Jasmine in the Angular ecosystem.</li>
<li><strong>Stronger mocking capabilities</strong> – Vitest provides a much more powerful mocking system, including the ability to mock entire ES modules.</li>
<li><strong>Explicit imports</strong> – Unlike Jasmine in the Angular CLI setup, Vitest does not rely on globals by default. Testing utilities such as <code>describe</code>, <code>it</code>, <code>expect</code>, and <code>vi</code> are typically imported explicitly (unless you opt into global mode).</li>
</ul>
<p>This gives you a high-level overview of how Vitest compares to the previous Angular testing stack.</p>
<p>Next, let’s explore the most fundamental concepts of Vitest, starting with the notion of <em>spying</em>.</p>
<h2 id="how-spying-works-in-vitest-understanding-vitest-spies">How Spying works in Vitest: Understanding Vitest Spies</h2>
<p>In Vitest, a spy is a tool that lets you observe how a function is being used during a test <em>without changing its actual behavior</em>.</p>
<p>This is especially useful when you want to verify not just the result of a function, but also <em>how</em> it was called.</p>
<p>For example, imagine a simple calculator module with an <code>add</code> method that adds two numbers and logs a message to the console:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">function</span> <span class="token function">add</span><span class="token punctuation">(</span>a<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">,</span> b<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'REAL add() called'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">export</span> <span class="token keyword">const</span> calculator <span class="token operator">=</span> <span class="token punctuation">{</span>
    add
<span class="token punctuation">}</span>
</code></pre></div>
<p>A normal test might simply check that <code>add(2, 3)</code> returns 5. However, sometimes that’s not enough.</p>
<p>You may also want to confirm that the function was called exactly once, and that it was called with the correct arguments.</p>
<p>That’s where spies come in.</p>
<p>Here is an example of how spying works in Vitest:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span>describe<span class="token punctuation">,</span> it<span class="token punctuation">,</span> expect<span class="token punctuation">,</span> vi<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vitest'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span>calculator<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"./calculator"</span><span class="token punctuation">;</span>

<span class="token function">describe</span><span class="token punctuation">(</span><span class="token string">"Vitest Fundamentals"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

    <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"should add two numbers"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>

    <span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how Vitest spies work"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token keyword">const</span> spy <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">spyOn</span><span class="token punctuation">(</span>calculator<span class="token punctuation">,</span> <span class="token string">"add"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledWith</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div>
<p>In the first test of this test suite, we are calling the actual calculator functionality, without any spies attached to it.</p>
<p>It's just a pure unit test.</p>
<p>In the second test though, we are attaching a Vitest spy to the calculator module, specifically to the add function.</p>
<p>The spy will by default observe the original <code>add()</code> function, <em>without</em> modifying its behavior.</p>
<p>And by that I mean that from the point of view of a user of the function, the calculator can still be called as usual, and the actual underlying <code>add</code> method will still be called.</p>
<p>But each time that <code>add()</code> is called, the spy is making note of it, and tracking the calls.</p>
<p>That is why we can assert in that second test that the <code>add()</code> function was only called once, and with the exact arguments 2 and 3.</p>
<p>And that is how spying works in Vitest: it's all about observing a behavior, without altering it. Next up, let's talk about mocking.</p>
<h1 id="how-mocking-works-in-vitest-understanding-vitest-mocks">How Mocking works in Vitest: Understanding Vitest Mocks</h1>
<p>Vitest mocking allows you to replace the real implementation of a function with a fake one.</p>
<p>This is useful when you want full control over what a dependency returns, without executing its real logic.</p>
<p>Notice that mocking can be used in combination with spying, and in fact the two techniques are often used together.</p>
<p>To understand how mocking works, consider the following test:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how Vitest mocking works"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> spy <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">spyOn</span><span class="token punctuation">(</span>calculator<span class="token punctuation">,</span> <span class="token string">"add"</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">mockReturnValue</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledWith</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token comment">// the result is always 5, due to mocking</span>
    <span class="token keyword">const</span> result2 <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div>
<p>Here, we start by creating a spy on the calculator <code>add</code>() function.</p>
<p>But unlike a simple spy, we chain <code>.mockReturnValue(5)</code>.</p>
<p>This changes the behavior of the function: instead of running the original add implementation, it will now always return 5, no matter what arguments are passed.</p>
<p>More than that, the actual <code>add()</code> implementation is completely bypassed!</p>
<p>When we call calculator.add(2, 3), the real addition logic is no longer executed.</p>
<p>The mocked version runs instead and immediately returns 5.</p>
<p>The same happens when we call calculator.add(5, 5) — even though the real result would be 10, the mocked function still returns 5.</p>
<p>At the same time, the spy continues tracking how the function is used.</p>
<p>We can still assert that it was called once, and that it was called with specific arguments.</p>
<p>So mocking with <code>mockReturnValue</code> gives us full control over the return value of the mocked function.</p>
<p>In short:</p>
<ul>
<li>spying observes calls but keeps the real implementation.</li>
<li>mocking replaces the implementation.</li>
</ul>
<p>You can still verify call count and arguments while controlling the return value.</p>
<h3 id="when-to-use-mocking">When to use mocking?</h3>
<p>Mocking is especially useful in real applications when you want to test a component in isolation from some of its dependencies.</p>
<p>These could be services with API calls, or complex dependencies where you don’t really want the actual logic to execute during the test, but instead you would want to replace that dependency with a mock.</p>
<p>In this example we have mocked an actual external module, and replaced the default functionality.</p>
<p>Let's now see another type of mocks in Vitest - pure mocks.</p>
<h2 id="pure-mocks-in-vitest">Pure mocks in Vitest</h2>
<p>When working with Vitest, most developers first encounter mocks in the context of replacing a specific method on an imported dependency.</p>
<p>In our previous example, we were spying on a real calculator <code>add()</code> method, and we were overriding just that particular function while leaving the rest of the module intact.</p>
<p>A pure mock, however, takes a different approach.</p>
<p>Instead of partially mocking a real dependency, you create a completely standalone mock function that has <strong>no underlying implementation at all</strong>.</p>
<p>A pure mock <em>doesn’t</em> wrap real code — instead, it just provides a completely fake alternative, with a similar API.</p>
<p>In Vitest, pure mocks are created using <code>vi.fn()</code>.</p>
<p>This utility returns a new mock function that can track how it was called and can be configured to return specific values.</p>
<p>For example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how a Vitest pure mock works"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> addMock <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">mockReturnValue</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token function">addMock</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>addMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>addMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledWith</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Here, <code>vi.fn()</code> creates a brand-new mock function.</p>
<p>By chaining <code>mockReturnValue(10)</code>, we define its behavior: regardless of the arguments passed, it will <em>always</em> return 10.</p>
<p>There is no real “add” implementation underneath — no logic that sums numbers.</p>
<p>The function is entirely synthetic, built purely for testing purposes.</p>
<p>But even though the mock has no real logic, Vitest still records how it is used.</p>
<p>That’s why we can assert that it was called exactly once and verify the exact arguments with which it was called.</p>
<h3 id="when-to-use-pure-mocks">When to use pure mocks?</h3>
<p>This dual capability — controlling return values while inspecting invocation details — makes pure mocks extremely powerful.</p>
<p>Pure mocks are especially useful when creating or instantiating a real dependency would be expensive, complex, or unnecessary for the test.</p>
<p>Instead of importing and partially mocking a module, you can replace the entire dependency with a lightweight fake implementation.</p>
<p>This approach keeps tests isolated, fast, and focused strictly on the behavior of the unit under test.</p>
<p>And that covers mocking and spying. If you also like to learn by watching videos, here is a free video introduction on how Vitest spies work (and more).</p>
<p>Check out the free sample video lessons available as part of the <a href="https://angular-university.io/course/angular-testing-in-depth" target="_blank" rel="noopener">Angular Testing In Depth (Signals Edition)</a> course:</p>
<p><a href="https://angular-university.io/course/angular-testing-in-depth" target="_blank" rel="noopener"><img src="https://d3vigmphadbn9b.cloudfront.net/course-images/large-images/angular-testing-In-depth.jpg" alt="" loading="lazy" decoding="async"></a></p>
<p>Now that we know about mocking and spying, let's talk about how to keep your tests well isolated from each other.</p>
<p>In Vitest, this involves 3 separate but highly inter-related concepts that we will cover one at a time: mock clearing, resetting and restoring.</p>
<p>Let's start with mock clearing.</p>
<h2 id="mock-clearing-understanding-mockclear">Mock clearing - understanding mockClear()</h2>
<p>When you create a spy in Vitest, that does a couple of things:</p>
<ul>
<li>The spy watches a function</li>
<li>The spy keeps track of how many times that function was called (and with what arguments).</li>
</ul>
<p>There could be situations in your tests, where you might want to clear that tracking data.</p>
<p>Mock clearing does exactly that - it resets the tracking data, but keeps the spy active.</p>
<p>That means the function is still being watched, but its “memory” of past calls is erased.</p>
<p>Here is an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how mock clearing works"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> spy <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">spyOn</span><span class="token punctuation">(</span>calculator<span class="token punctuation">,</span> <span class="token string">"add"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    spy<span class="token punctuation">.</span><span class="token function">mockClear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result2 <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Let's break down what is going on here:</p>
<ul>
<li>A spy was created on the real add method.</li>
<li>The first call <code>add(2, 3)</code> runs the real function and the spy records 1 call.</li>
<li>Then <code>mockClear()</code> wipes the spy’s call history.</li>
<li>The second call <code>add(5, 5)</code> runs the real function again.</li>
</ul>
<p>So now the spy sees the second call as #1, because its history was cleared.</p>
<p>Even though add was called twice in total, the spy now only remembers calls made <em>after</em> <code>mockClear()</code>.</p>
<p>You can think of <code>mockClear()</code> like this:</p>
<blockquote>
<p>Keep watching the function — but forget everything that happened before.</p>
</blockquote>
<p>Calling <code>mockClear()</code> cleans up call counts, but it does not:</p>
<ul>
<li>Remove the spy</li>
<li>Restore the original function</li>
<li>Change the implementation</li>
</ul>
<p>It just clears the call history.</p>
<p>So that’s mock clearing in a nutshell. Next up, let's talk about mock resetting.</p>
<h2 id="mock-resetting-understanding-mockreset">Mock resetting - understanding mockReset()</h2>
<p>Vitest has a couple of “cleanup” operations for mocks, and it’s easy to mix them up until you see them side by side.</p>
<p>Mock resetting does everything a clear does plus removes any custom mock behavior.</p>
<p>In other words, <code>mockReset()</code> wipes the mock’s recorded state (calls, arguments, instances, etc.), <em>and</em> it removes any configured behavior such as<br>
<code>mockReturnValue</code> or <code>mockImplementation</code>.</p>
<p>What “default behavior” means depends on what you’re resetting.</p>
<p>With a spy, there’s a real function underneath.</p>
<p>When you call <code>mockReset()</code> on a spy, it keeps the spy in place but removes the mocked return value or implementation you provided.</p>
<p>After that, calls go through to the original function again. You can see that in this test:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how mockReset() works for Vitest spies"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> spy <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">spyOn</span><span class="token punctuation">(</span>calculator<span class="token punctuation">,</span> <span class="token string">"add"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    spy<span class="token punctuation">.</span><span class="token function">mockReturnValue</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// result is 10, independently of </span>
    <span class="token comment">//the calling arguments</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    spy<span class="token punctuation">.</span><span class="token function">mockReset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result2 <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// the actual add function is now called again</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Before the reset, the original <code>calculator.add()</code> implementation is completely bypassed and always returns 10.</p>
<p>After <code>mockReset()</code>, the custom return value is gone, so <code>add(2, 3)</code> behaves normally again and returns 5.</p>
<p>Notice that the call history is also cleared—so the post-reset invocation is treated as the first call.</p>
<h3 id="how-does-mockreset-work-for-pure-mocks">How does mockReset work for pure mocks?</h3>
<p>With a pure mock (created using <code>vi.fn()</code>), and unlike spies, there is no underlying real implementation.</p>
<p>A pure mock starts with no behavior, which means calling it returns undefined unless you configure it.</p>
<p>When you call <code>mockReset()</code> on a pure mock, it clears the call history and removes the configured behavior, bringing it back to having no implementation:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how mockReset() works for pure mocks"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> addMock <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">mockReturnValue</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token function">addMock</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>addMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>addMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledWith</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    addMock<span class="token punctuation">.</span><span class="token function">mockReset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result2 <span class="token operator">=</span> <span class="token function">addMock</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token keyword">undefined</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>addMock<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The key mental model is this:</p>
<blockquote>
<p>clearing is about resetting state (what happened), while resetting is state plus behavior (what it does).</p>
</blockquote>
<p>For spies, that means removing the mocked behavior so calls flow through to the original function.</p>
<p>For pure mocks, it means removing the mocked behavior so the function goes back to returning undefined.</p>
<p>So this covers resetting, leaving only one final concept to cover: mock restoring.</p>
<h2 id="mock-restoring-understanding-mockrestore">Mock restoring - understanding mockRestore()</h2>
<p>When you use <code>vi.spyOn()</code> in Vitest, you’re temporarily replacing a real method with a spy wrapper.</p>
<p>That wrapper both tracks how the function is used and lets you override its behavior.</p>
<p>But once a test is done, you usually want everything to go back to normal, by disconnecting the spy from the actual implementation.</p>
<p>And that’s where <code>mockRestore()</code> comes in.</p>
<p>The simplest way to understand <code>mockRestore()</code> is to think of it as doing three things at once: clear, reset, and restore.</p>
<ul>
<li>First, it clears the call history — any recorded calls, arguments, and return values are wiped.</li>
<li>Second, it resets the mocked behavior — meaning any mockReturnValue or mockImplementation you defined is removed.</li>
<li>Third, it restores and disconnects — the original real function is put back onto the object, and the spy wrapper is completely removed. Future calls go directly to the real implementation and are no longer tracked.</li>
</ul>
<p>Here’s a small test that demonstrates the full lifecycle:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">it</span><span class="token punctuation">(</span><span class="token string">"shows how mockRestore() works"</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> spy <span class="token operator">=</span> vi<span class="token punctuation">.</span><span class="token function">spyOn</span><span class="token punctuation">(</span>calculator<span class="token punctuation">,</span> <span class="token string">"add"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    spy<span class="token punctuation">.</span><span class="token function">mockReturnValue</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledOnce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    spy<span class="token punctuation">.</span><span class="token function">mockRestore</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">const</span> result2 <span class="token operator">=</span> calculator<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>result2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">expect</span><span class="token punctuation">(</span>spy<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toHaveBeenCalledTimes</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Let’s break it down.</p>
<p>We start by spying on <code>calculator.add</code>, which replaces the real method with a spy wrapper. Then we override its behavior so that add(2, 3) returns 10 instead of 5. The spy tracks that it was called once.</p>
<p>When spy.mockRestore() runs, Vitest clears the call history, removes the mocked return value, and re-installs the original add implementation. The spy is now fully disconnected.</p>
<p>So when we call calculator.add(2, 3) again, it returns 5 — the real logic is back.</p>
<p>And because the spy was cleared and detached, it reports zero calls.</p>
<h3 id="why-use-mockrestore">Why use <code>mockRestore</code>?</h3>
<p>In practice, you usually want to disconnect all spies between tests to avoid test pollution.</p>
<p>If you leave spies attached, mocked behavior can accidentally leak into later tests and cause confusing failures.</p>
<p>That’s why many test setups include an afterEach hook like this:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">afterEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    vi<span class="token punctuation">.</span><span class="token function">restoreAllMocks</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>This ensures every spy is restored and disconnected after each test, keeping your test suite isolated and predictable.</p>
<p>In the next section, I'm going to show you a better way of doing this.</p>
<h2 id="configuring-vitest-to-clean-up-between-tests">Configuring Vitest to clean up between tests</h2>
<p>As you imagine, it's best to clean up all spies between each test, and never reuse any spies or mocks across tests.</p>
<p>Ideally each test creates all the mocks and spies that it needs to run, and then it cleans up everything in the end.</p>
<p>If we don't do so, we might accidentally introduce erratic behavior in our tests.</p>
<p>For example, the tests might start failing if we run them in a different order, etc.</p>
<p>To avoid all this, it's best to automatically cleanup everything after each test.</p>
<p>Instead of relying on local <code>beforeEach</code> functions, we can also do that globally via configuration:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">    <span class="token keyword">import</span> <span class="token punctuation">{</span> defineConfig <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vitest/config'</span><span class="token punctuation">;</span>
    
    <span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token function">defineConfig</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    test<span class="token operator">:</span> <span class="token punctuation">{</span>
    globals<span class="token operator">:</span><span class="token boolean">false</span><span class="token punctuation">,</span>
    environment<span class="token operator">:</span><span class="token string">'jsdom'</span><span class="token punctuation">,</span>
    include<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">'src/**/*.spec.ts'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    restoreMocks<span class="token operator">:</span> <span class="token boolean">true</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>This has the effect of ensuring that every test cleans up after itself automatically.</p>
<p>Notice that there are other flags for resetting and clearing as well:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">    <span class="token keyword">import</span> <span class="token punctuation">{</span> defineConfig <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vitest/config'</span><span class="token punctuation">;</span>
    
    <span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token function">defineConfig</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    test<span class="token operator">:</span> <span class="token punctuation">{</span>
    globals<span class="token operator">:</span><span class="token boolean">false</span><span class="token punctuation">,</span>
    environment<span class="token operator">:</span><span class="token string">'jsdom'</span><span class="token punctuation">,</span>
    include<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">'src/**/*.spec.ts'</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    restoreMocks<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    clearMocks<span class="token operator">:</span><span class="token boolean">true</span><span class="token punctuation">,</span>
    mockReset<span class="token operator">:</span><span class="token boolean">true</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>In practice, you should't need all 3. But if by some reason you need them, now you know that they are there.</p>
<p>And with this, we have covered the fundamental concepts of Vitest.</p>
<p>Let's now summarize everything, and wrap things up.</p>
<h2 id="conclusions">Conclusions</h2>
<p>Vitest represents more than just a replacement for Karma and Jasmine — it introduces a simpler mental model, a <strong>faster execution environment</strong>, and a significantly more powerful mocking system.</p>
<p>By integrating the test runner directly into the framework, Vitest eliminates the complexity of coordinating multiple tools. Combined with its lightweight DOM environments and optional real browser mode, it offers both speed and flexibility depending on your testing needs.</p>
<p>At the API level, the familiar describe / it / expect structure makes the transition smooth for Angular developers.</p>
<p>But under the surface, Vitest provides:</p>
<ul>
<li>stronger assertions</li>
<li>first-class module mocking</li>
<li>explicit control over test utilities</li>
</ul>
<p>All of which encourage clearer and more intentional test design.</p>
<p>Understanding the <strong>differences between spies, mocks, and pure mocks</strong> is key:</p>
<ul>
<li>
<p>Use spies when you want to <strong>observe real behavior</strong> without changing it.</p>
</li>
<li>
<p>Use mocks when you need to <strong>override behavior while still tracking</strong> usage.</p>
</li>
<li>
<p>Use pure mocks when you want a <strong>fully synthetic dependency</strong> with no real implementation underneath.</p>
</li>
</ul>
<p>Equally important is mastering test isolation. Knowing when to use mockClear(), mockReset(), and mockRestore() ensures your tests remain predictable and independent.</p>
<p>Proper cleanup — ideally automated via configuration — prevents test pollution and avoids subtle, order-dependent failures.</p>
<h3 id="spying-mocking-when-to-use-each-and-why">Spying, Mocking .. when to use each and why?</h3>
<p>In practice, a good rule of thumb is this:</p>
<ul>
<li>
<p>Prefer <strong>spying on real functionality</strong> when you want confidence that real logic executes correctly while still verifying interactions.</p>
</li>
<li>
<p>Prefer pure mocks when the real implementation is irrelevant, slow, complex, or tied to external systems such as APIs.</p>
</li>
</ul>
<p>Vitest gives you precise control over both approaches, allowing you to write tests that are fast, expressive, and isolated — without sacrificing clarity.</p>
<p>With these fundamentals in place, you now have a solid foundation for writing robust Angular tests with Vitest.</p>
<p>In upcoming articles, we’ll build on this knowledge and explore Angular-specific testing patterns.</p>
<p>Subscribe to my newsletter if you want me to send you the next articles to your mailbox:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
]]></content:encoded>
    </item>
    <item>
      <title>Angular linkedSignal(): The Missing Link in Signal-Based Reactivity</title>
      <link>https://blog.angular-university.io/angular-linkedsignal/</link>
      <guid isPermaLink="false">67d2fc7a921ab5000140b1c8</guid>
      <pubDate>Fri, 14 Mar 2025 17:11:07 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>Angular’s linkedSignal is a key addition to the Angular Signals API - it enables certain edge cases to be easily implemented with signals in a much more reactive and declarative way.</description>
      <content:encoded><![CDATA[<p>The Angular signal-based reactivity system provides powerful primitives like<br>
<code>signal</code>, <code>computed</code>, and <code>effect</code> to manage state reactively.</p>
<p>But in certain edge cases, something <strong>seemed</strong> to be missing ... until now!</p>
<p>Before linked signals, there used to be certain edge cases where there just wasn't a great way to implement those scenarios using a signal-based approach.</p>
<p>It's not that we couldn't make it work with signals for those scenarios.</p>
<p>But the signal-based code for those specific scenarios was just a bit awkward and verbose, and it just didn't feel right.</p>
<p>The good news is that linked signals solve many of these edge cases in a much more elegant way.</p>
<p>In this post, we’ll explore in detail what a linked signal is, when to use it and why.</p>
<h1 id="table-of-contents">Table of Contents</h1>
<p>This post covers the following topics:</p>
<ul>
<li>What is an Angular Linked Signal?</li>
<li>Key Features of <code>linkedSignal</code></li>
<li>What does a linked signal look like?</li>
<li>When is a linked signal useful?</li>
<li>How to implement a linked signal</li>
<li>So why not just use linkedSignal everywhere, instead of computed?</li>
<li>Common examples of when to use linked signals</li>
<li>Conclusion</li>
</ul>
<p>Notice that linked signals are strongly related to the other Angular signal primitives: signal, computed, and effect.</p>
<p>So if you haven't done so already, I recommend that you read first this other guide: <a href="https://blog.angular-university.io/angular-signals/">Angular Signals: The Complete Guide</a>.</p>
<h2 id="what-is-an-angular-linked-signal">What is an Angular Linked Signal?</h2>
<p>A <code>linkedSignal</code> is a new primitive in Angular’s signal API that allows a writable signal to be linked to one or more source signals.</p>
<p>Unlike a <code>computed</code> signal, which is read-only, a <code>linkedSignal</code> maintains a reactive relationship with its sources while still being writable.</p>
<h3 id="key-features-of-linkedsignal">Key Features of <code>linkedSignal</code>:</h3>
<p>Here are the key features of <code>linkedSignal</code>:</p>
<ul>
<li><strong>Writable:</strong> Unlike <code>computed</code>, which is read-only, a <code>linkedSignal</code> allows direct updates via the <code>set</code> or <code>update</code> methods.</li>
<li><strong>Reactive:</strong> Exactly like <code>computed</code>, it derives its value from one or more source signals.</li>
</ul>
<p>Let's have a look at some code to understand how it works.</p>
<h3 id="what-does-a-linked-signal-look-like">What does a linked signal look like?</h3>
<p>Here is a simple example:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">const</span> quantity <span class="token operator">=</span> <span class="token function">linkedSignal</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token function-variable function">source</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token punctuation">{</span> courseCode<span class="token operator">:</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">selectedCourse</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token function-variable function">compute</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">{</span> courseCode <span class="token punctuation">}</span><span class="token punctuation">,</span> previous<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> course <span class="token operator">=</span> 
    <span class="token keyword">this</span><span class="token punctuation">.</span>courses<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span>c <span class="token operator">=></span> c<span class="token punctuation">.</span>code <span class="token operator">===</span> courseCode<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> 
      course <span class="token operator">?</span> course<span class="token punctuation">.</span>defaultQuantity <span class="token operator">:</span> previous <span class="token operator">??</span> <span class="token number">1</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The key elements to understand linked signals are:</p>
<ul>
<li><strong>source:</strong> The source signal that the linked signal derives its value from.</li>
<li><strong>compute:</strong> The function that computes the value of the linked signal.</li>
</ul>
<p>So <code>quantity</code> is a linked signal that derives its value from the <code>selectedCourse</code> source signal.</p>
<p>Here is what is going on in more detail:</p>
<ul>
<li>The <code>source</code> function defines the source signals that the linked signal is linked to.</li>
<li>The <code>compute</code> function is called whenever any of the source signals emit a new value.</li>
<li><code>compute</code> receives the latest value of the source signals and the previous value of the linked signal.</li>
<li>It then returns the new value of the linked signal, which get's emitted to the consumers of the linked signal.</li>
</ul>
<p>So in this case, the linked signal <code>quantity</code> will be updated whenever the <code>selectedCourse</code> signal changes.</p>
<p>So it really sounds just like a <code>computed</code> signal, right?</p>
<p>The difference is that, unlike <code>computed</code>, a linked signal is writable.</p>
<p>Unlike <code>computed</code>, you can update the value of the linked signal using the <code>set</code> or <code>update</code> methods like so:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">quantity<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
quantity<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>current <span class="token operator">=></span> current <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>So as we we can see, <code>linkedSignal</code> is kind of a combination between the <code>computed</code> and <code>signal</code> primitives, all mixed into one.</p>
<p>So that's essentially what it is, but I bet you are still wondering why it's needed and why it's useful.</p>
<h3 id="when-is-a-linked-signal-useful">When is a linked signal useful?</h3>
<p>To understand when a linked signal is useful, let's use a simple but still realistic example.</p>
<p>Let's say that we have a shopping cart, and that the user can add items to the cart and select the quantity of each item.</p>
<p>Each item on the list has a default quantity.</p>
<p>So if the user changes the selected product to add to the cart, the quantity should be reset to the default quantity of the selected product.</p>
<p>Here is what the html of the shopping cart component might look like:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>demo-container<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Shopping Cart<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>form-control<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span><span class="token punctuation">></span></span>Select Course<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">[value]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>selectedCourse()<span class="token punctuation">"</span></span> 
    <span class="token attr-name">(change)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>onCourseSelected(course.value)<span class="token punctuation">"</span></span> <span class="token attr-name">#course</span><span class="token punctuation">></span></span>
      @for (course of courses; track course.code) {
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>option</span> <span class="token attr-name">[value]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>course.code<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
            {{course.title}}
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>option</span><span class="token punctuation">></span></span>
      }
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>form-control<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span><span class="token punctuation">></span></span>Quantity<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>number<span class="token punctuation">"</span></span> 
       <span class="token attr-name">[value]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>quantity()<span class="token punctuation">"</span></span> 
       <span class="token attr-name">(change)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>onQuantityChanged(input.value)<span class="token punctuation">"</span></span>
       <span class="token attr-name">#input</span><span class="token punctuation">/></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>form-actions<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>btn<span class="token punctuation">"</span></span> 
            <span class="token attr-name">(click)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>onArticleAdded()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
      Add To Cart
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

</code></pre></div>
<p>So let's break down what is going on here:</p>
<ul>
<li>everything is done with signals: the selected course is a signal, the quantity is a signal, and the courses list is also a signal.</li>
<li>We have a list of courses, and the user can select one of them to add to the cart.</li>
<li>The quantity of the item to add to the cart is displayed in the quantity input field.</li>
<li>The quantity input field is linked to the selected course.</li>
<li>When the user changes the selected course, the quantity input field is reset to the default quantity of the selected course.</li>
</ul>
<p>The quantity signal is the key part of this example.</p>
<p>It needs to be reset to the default quantity of the selected course, every time the user chooses a new course from the dropdown.</p>
<p>But it also needs to be writable, so the user can change the quantity manually.</p>
<h3 id="so-how-do-we-implement-this-scenario">So how do we implement this scenario?</h3>
<p>Well, we could use a <code>computed</code> signal to compute the quantity based on the selected course.</p>
<p>But a <code>computed</code> signal is read-only, so we wouldn't be able to reset the quantity to the default quantity of the selected course when the user changes the selected course.</p>
<p>Alternatively, we could use an <code>effect</code> to update the quantity whenever the selected course changes.</p>
<p>that would look like this:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> selectedCourse <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">selectedCourse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  quantity<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>
      courses<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span>
      c <span class="token operator">=></span> c<span class="token punctuation">.</span>code <span class="token operator">===</span> 
      selectedCourse<span class="token punctuation">)</span><span class="token operator">?.</span>defaultQuantity <span class="token operator">??</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>So it works, right? Well kind of.</p>
<h3 id="why-not-just-use-an-effect">Why not just use an effect?</h3>
<p>This could work, but it feels a bit awkward.</p>
<p>It's just not very declarative, as we are writing the value imperatively of the quantity signal inside the effect.</p>
<p>Writing signal values inside effects is now possible, but it's still not a good idea, as it could easily create infinite loops.</p>
<p>It's not very obvious either that the quantity signal is linked to the selected course signal,just by looking at the signal declarations.</p>
<p>It's not that it can't be made to work, but it just feels wrong.</p>
<p>Effects are meant to be used for pure side effects, and not for this kind of reactive value computation where we are linking signals together.</p>
<p>Also, in general it's a good idea to avoid effects as much as possible, and only use them as a last resort.</p>
<h3 id="so-what-s-the-alternative">So what's the alternative?</h3>
<p>Well, that's where <code>linkedSignal</code> comes in.</p>
<p>Here is the complete component, written with a linked signal:</p>
<div class="code-block"><span class="code-lang">typescript</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">'linked-signal-demo'</span><span class="token punctuation">,</span>
  templateUrl<span class="token operator">:</span> <span class="token string">'./linked-signal-demo.component.html'</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">LinkedSignalDemoComponent</span> <span class="token punctuation">{</span>

  <span class="token comment">// these are the products of the shopping cart </span>
  courses <span class="token operator">=</span> <span class="token punctuation">[</span>
    <span class="token punctuation">{</span>
      code<span class="token operator">:</span> <span class="token string">"BEGINNERS"</span><span class="token punctuation">,</span>
      title<span class="token operator">:</span> <span class="token string">"Angular for Beginners"</span><span class="token punctuation">,</span>
      defaultQuantity<span class="token operator">:</span> <span class="token number">10</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span>
      code<span class="token operator">:</span> <span class="token string">"SIGNALS"</span><span class="token punctuation">,</span>
      title<span class="token operator">:</span> <span class="token string">"Angular Signals In Depth"</span><span class="token punctuation">,</span>
      defaultQuantity<span class="token operator">:</span> <span class="token number">20</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span>
      code<span class="token operator">:</span> <span class="token string">"SSR"</span><span class="token punctuation">,</span>
      title<span class="token operator">:</span> <span class="token string">"Angular SSR In Depth"</span><span class="token punctuation">,</span>
      defaultQuantity<span class="token operator">:</span> <span class="token number">30</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">]</span><span class="token punctuation">;</span>

  <span class="token comment">// this is the product that the user has </span>
  <span class="token comment">// selected to add to the cart </span>
  selectedCourse <span class="token operator">=</span> 
  <span class="token generic-function"><span class="token function">signal</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token builtin">string</span> <span class="token operator">|</span> <span class="token keyword">null</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token string">"BEGINNERS"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// this is the quantity of the product that the user </span>
  <span class="token comment">// has selected to add to the cart </span>
  <span class="token comment">// it needs to be reset to the default quantity </span>
  <span class="token comment">// of the last selected product, </span>
  <span class="token comment">// when the user changes the selected product</span>
  quantity <span class="token operator">=</span> <span class="token function">linkedSignal</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token function-variable function">source</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token punctuation">{</span>courseCode<span class="token operator">:</span> <span class="token keyword">this</span><span class="token punctuation">.</span>selectedCourse<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token function-variable function">computation</span><span class="token operator">:</span> <span class="token punctuation">(</span>source<span class="token punctuation">,</span> previous<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> 
      <span class="token keyword">this</span><span class="token punctuation">.</span>courses<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span>c <span class="token operator">=></span> c<span class="token punctuation">.</span>code 
      <span class="token operator">===</span> source<span class="token punctuation">.</span><span class="token function">courseCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">?.</span>defaultQuantity <span class="token operator">??</span> <span class="token number">1</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">onQuantityChanged</span><span class="token punctuation">(</span>quantity<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>quantity<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token function">parseInt</span><span class="token punctuation">(</span>quantity<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">onCourseSelected</span><span class="token punctuation">(</span>courseCode<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>selectedCourse<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>courseCode<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>So as you can see, the <code>linkedSignal()</code> solves this scenario in a much more elegant and declarative way.</p>
<p>The dependency between the <code>selectedCourse</code> and <code>quantity</code> signals is now made very explicit, we can see it just by looking at the signal declarations, which is great.</p>
<p>And the quantity signal is still writable, so the user can change the quantity manually.</p>
<p>If the user changes the selected course, the quantity will be reset to the default quantity of that same selected course.</p>
<p>Exactly what we wanted to achieve, and no effects were needed!</p>
<h3 id="so-why-not-just-use-linkedsignal-everywhere-instead-of-computed">So why not just use linkedSignal everywhere, instead of computed?</h3>
<p>Well, that's a good question.</p>
<p>The answer is that linked signals are not meant to replace computed signals, plain signals, or even effects.</p>
<p>They are a new primitive that fills a specific gap in the signal API.</p>
<p>They are not meant to be used everywhere, but only in very specific and relatively rare scenarios where you need both reactivity and the ability to change a value at the same time.</p>
<p>If you can solve a problem with a computed signal, then there is no need to use a linkedSignal.</p>
<p>If you just need a writeable signal, you should use just a plain signal, which is writeable by default.</p>
<p>Linked signals should only be needed every so often.</p>
<p>In most cases, the signal and computed primitives are more than enough to solve the vast majority of problems, and they should be our go-to default.</p>
<h2 id="common-examples-of-when-to-use-linked-signals">Common examples of when to use linked signals</h2>
<p>Here are some common examples that you might run into where linked signals could be useful:</p>
<ul>
<li><strong>Form field resets based on another field’s value.</strong></li>
<li><strong>State management scenarios where values need to reset reactively but still allow user overrides.</strong></li>
<li><strong>If you are in a situation where computed signals are too restrictive, but effects feel too imperative, a linkedSignal might work better.</strong></li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p>The <code>linkedSignal</code> primitive fills an important gap in Angular’s signal-based reactivity model.</p>
<p>It allows developers to define reactive yet writable relationships between signals, making it perfect for cases like field resets and other scenarios.</p>
<p>While it’s not meant to replace <code>computed</code> or <code>signal</code> at all, it provides a powerful alternative when writable computed values are needed.</p>
<p>If you’re already using Angular’s signal API, give <code>linkedSignal</code> a go — it will help make your code cleaner and more maintainable.</p>
<p>But still try to solve most problems with the <code>computed</code> and <code>signal</code> primitives, as they are more than enough for most scenarios.</p>
<p>For more in-depth signals content, check out my <a href="https://angular-university.io/course/angular-signals-course" target="_blank" rel="noopener">Modern Angular with Signals Course</a> at the <a href="https://angular-university.io/" target="_blank" rel="noopener">Angular University</a>. 🚀</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Signal Queries: viewChild, contentChild, viewChildren, contentChildren (Complete Guide)</title>
      <link>https://blog.angular-university.io/angular-viewchild-contentchild/</link>
      <guid isPermaLink="false">6641fabfff78ae0001daf30c</guid>
      <pubDate>Mon, 27 May 2024 07:45:31 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>A super-detailed guide to the new Angular signal queries: viewChild(), viewChildren, contentChild() and contentChildren().</description>
      <content:encoded><![CDATA[<p>With the advent of Signals in Angular, we now have available a brand new way of authoring components in Angular using signal-based APIs, and <em>without</em> decorators.</p>
<p>A big part of this new way of writing components is the introduction of <strong>signal-based template queries</strong>:</p>
<ul>
<li>viewChild()</li>
<li>contentChild()</li>
<li>viewChildren()</li>
<li>contentChildren()</li>
</ul>
<p>These APIs are a new signal-based alternative to the traditional decorator-based template queries like <code>@ViewChild</code>, <code>@ContentChild</code>, <code>@ViewChildren</code>, and<br>
<code>@ContentChildren</code>.</p>
<p>They work in the exact same way, except that:</p>
<ul>
<li>they are signal-based</li>
<li>they are easier to understand and use</li>
<li>they are easy to integrate with other signals</li>
<li>and they usually don't require the need for lifecycle hooks</li>
</ul>
<p>In this comprehensive guide, we'll delve into the intricacies of these signal queries, exploring their syntax, usage patterns, and advantages over traditional decorator-based queries.</p>
<p>Whether you're a seasoned Angular developer or a newcomer, there is something for everybody in this guide.</p>
<p>So without further ado, let's dive right in!</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>What is viewChild()?</li>
<li>Querying plain HTML elements with viewChild()</li>
<li>What happens if the value of a template variable occurs more than once</li>
<li>viewChild() and Component Queries</li>
<li>How does the viewChild() signal query work?</li>
<li>Setting &quot;read&quot; on viewChild()</li>
<li>Making viewChild() to be required</li>
<li>What is viewChildren()?</li>
<li>Query components with <code>viewChildren()</code></li>
<li>Query-based on template references with <code>viewChildren()</code></li>
<li>viewChildren() arguments</li>
<li>Read different types of elements with <code>viewChildren()</code></li>
<li>Differences between <code>viewChildren()</code> and <code>viewChild()</code> signal queries</li>
<li>What is contentChild()?</li>
<li>contentChild and template reference variables</li>
<li>contentChild() and Component Queries</li>
<li>Deriving values from contentChild() signal</li>
<li>Responding to contentChild() changes</li>
<li>Using &quot;read&quot; on contentChild()</li>
<li>Making contentChild() to be required</li>
<li>What is contentChildren()?</li>
<li>Querying multiple elements with <code>contentChildren()</code></li>
<li>Querying multiple components with <code>contentChildren()</code></li>
<li>Read different types of elements with <code>contentChildren()</code> using the <code>read</code> option</li>
<li>Traverse into projected content descendants with <code>contentChildren()</code></li>
<li>Can I get undefined in my viewChild and contentChild queries?</li>
<li>Can we call viewChild, contentChild outside of component and directive property initializers?</li>
<li>Advantages of signal queries over decorator-based queries</li>
<li>Summary</li>
</ul>
<h2 id="related-posts">Related posts</h2>
<p>Notice that this post covers only the new signal-based alternatives for template querying. If you are looking to learn about the previous @ViewChild, @ViewChildren, you can read all about them here:</p>
<p><a href="https://blog.angular-university.io/angular-viewchild/">Angular @ViewChild: In-Depth Explanation (All Features Covered)</a></p>
<p>And if you are looking to learn about the previous @ContentChild, @ContentChildren you can read all about it here:</p>
<p><a href="https://blog.angular-university.io/angular-ng-content/">Angular ng-content and Content Projection: Complete Guide</a></p>
<h2 id="what-is-viewchild">What is viewChild()?</h2>
<p><code>viewChild</code> is a signal-based query used to retrieve elements from the component's template.</p>
<p>These elements can be either instances of other Angular components or just plain HTML elements.</p>
<p>The <code>viewChild</code> signal query does the same thing as the @ViewChild decorator.</p>
<p>Let's start by learning how to query plain HTML elements, and later we will learn how to query components.</p>
<h2 id="querying-plain-html-elements-with-viewchild">Querying plain HTML elements with viewChild()</h2>
<p>To query an element from the template, we need to assign it a template reference, using the # syntax.</p>
<p>Here is how it works:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;b #title>Title&lt;/b>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

    title <span class="token operator">=</span> <span class="token generic-function"><span class="token function">viewChild</span><span class="token generic class-name"><span class="token operator">&lt;</span>ElementRef<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token string">"title"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
            <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Title: "</span><span class="token punctuation">,</span> 
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">title</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">?.</span>nativeElement<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we have assigned the #title template reference to the <strong>native HTML element</strong>.</p>
<p>Then we used the <code>viewChild</code> signal query to query the HTML element with the template reference named #title.</p>
<p>The <code>viewChild</code> signal query returns a signal whose emitted value <em>is</em> the queried element itself, although wrapped in an <code>ElementRef</code>.</p>
<p>So if we want access to the result of the query, all we have to do is to subscribe to the <code>title</code> query signal using any of the signal-based APIs like <code>effect()</code> or<br>
<code>computed()</code>.</p>
<h2 id="what-is-the-value-returned-by-this-signal">What is the value returned by this signal?</h2>
<p>Notice that to access the actual native HTML element, we still have to access the nativeElement property of the signal value.</p>
<p>This is because <code>ElementRef</code> is a wrapper to the actual DOM element, and not the element itself.</p>
<h2 id="why-did-we-use-a-generic-parameter-elementref">Why did we use a generic parameter ElementRef?</h2>
<p>Notice also that we used generic parameter <code>&lt;ElementRef&gt;</code> on viewChild, to indicate the type of values emitted by the query signal.</p>
<p>If we haven't done so, the signal would be considered to emit values ot type<br>
<code>unknown</code>, which is <em>not</em> what we want.</p>
<p>And this is how you query native HTML elements using the <code>viewChild()</code> signal query, it's that simple!</p>
<h2 id="what-about-afterviewinit">What about AfterViewInit?</h2>
<p>Notice that we didn't have to use the typical <code>AfterViewInit</code> lifecycle hook like we used to do when using the @ViewChild decorator.</p>
<p>Instead, we just used a plain signal effect() to get notified when the title element is ready.</p>
<p>We could also have used computed() to derive values from the title signal.</p>
<p>The title signal is just a plain read-only signal, so it's very easy to work with and integrates seamlessly with the other signal-based constructs of the framework.</p>
<p>This means that in principle we shouldn't need AfterViewInit anymore when using query signals instead of their decorator equivalent.</p>
<h2 id="what-happens-if-the-value-of-a-template-variable-occurs-more-than-once">What happens if the value of a template variable occurs more than once?</h2>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>b</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>First Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>b</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>b</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Second Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>b</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Paragraph Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>b</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>In this case, <code>viewChild</code> will pick the first occurrence of the <code>title</code> variable, and no error will be thrown.</p>
<h2 id="viewchild-and-component-queries">viewChild() and Component Queries</h2>
<p>Besides plain HTML elements, we can also query <strong>component instances</strong> using the <code>viewChild</code> feature.</p>
<p>We can query components either by using template references like before, or by using the component class itself.</p>
<p>Let's start with querying components using template references:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book #book>&lt;/book>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
  bookComponent <span class="token operator">=</span> 
  <span class="token generic-function"><span class="token function">viewChild</span><span class="token generic class-name"><span class="token operator">&lt;</span>BookComponent<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token string">"book"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we are using here a <code>&lt;book/&gt;</code> component in our template, and it has a template reference variable, <code>book</code>.</p>
<p>If we pass this <code>book</code> reference to <code>viewChild</code>, the query signal will return the instance of the <code>BookComponent</code>, and <em>not</em> the corresponding HTML element.</p>
<p>This means that we can interact with the component instance directly, like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">bookComponent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>title<span class="token punctuation">;</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">bookComponent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Notice the use of the generic parameter <code>&lt;BookComponent&gt;</code>. This parameter is essential to tell viewChild what type of component is expected to match this query.</p>
<p>And this is how you use <code>viewChild</code> to directly query component instances, it's that simple!</p>
<h2 id="how-does-viewchild-work-if-the-template-changes">How does viewChild() work if the template changes?</h2>
<p>The <code>viewChild</code> signal query initially performs the query when the view is initialized.</p>
<p>If at any point the queried element is destroyed, re-rendered, or updated from the component tree, then the signal query will perform the query again to update itself to the current state of the element.</p>
<p>If the element is destroyed then the value of the signal query will be undefined.</p>
<p>But when created again, the signal query will get the element from the template view again.</p>
<p>So as you can see, the signal query refreshes itself at every change detection run.</p>
<h2 id="setting-read-on-viewchild">Setting &quot;read&quot; on viewChild()</h2>
<p>By default, the <code>viewChild()</code> query will emit as value:</p>
<ul>
<li>an <code>ElementRef</code> instance if the queried element is a plain HTML element</li>
<li>a component instance if the queried element is a component</li>
</ul>
<p>But this is just the default behavior, we can change it if necessary!</p>
<p>And there are valid cases when we would like to do so.</p>
<p>For example, even if the queried element is a component, we might still want to access its HTML element for some reason.</p>
<p>So here is how we would do it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book #book>&lt;/book>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
  bookComponent <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span><span class="token string">"book"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
    read<span class="token operator">:</span> ElementRef
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This &quot;read&quot; configuration tells <code>viewChild()</code> to emit as value the <code>ElementRef</code> of the queried element, and <em>not</em> the component that is linked to it.</p>
<p>Besides this, there are other user cases where we would want to use the &quot;read&quot; option.</p>
<p>For example, the queried element might have several directives applied to it, and we might want to query them separately.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book #book 
       matTooltip="I'm a tooltip!"> 
      &lt;/book>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
    imports<span class="token operator">:</span> <span class="token punctuation">[</span>
        MatTooltip
    <span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
    bookComponent <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span><span class="token string">"book"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
        read<span class="token operator">:</span> MatTooltip
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
            <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Tooltip: "</span><span class="token punctuation">,</span> 
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">bookComponent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">?.</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In this case, the emitted value of the <code>viewChild()</code> query will be the <code>MatTooltip</code> directive instance, and <em>not</em> the <code>BookComponent</code> instance.</p>
<p>So if an element has several different directives applied to it, we can use the &quot;read&quot; option to query them separately one by one, if necessary.</p>
<h2 id="making-viewchild-to-be-required">Making viewChild() to be required</h2>
<p>By default, viewChild() will return undefined if the queried element is not found in the template view.</p>
<p>But we can make <code>viewChild()</code> make queries that should <em>always</em> match something in the template view.</p>
<p>If there is no match for the query, then an error will be thrown:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>b</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>b</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
</code></pre></div>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">titleRef <span class="token operator">=</span> viewChild<span class="token punctuation">.</span><span class="token function">required</span><span class="token punctuation">(</span><span class="token string">"bold"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>As the above query has no match, the following error will be thrown:</p>
<blockquote>
<p>ERROR Error: NG0951: Child query result is required but no value is available.</p>
</blockquote>
<p>And with this, we have finished our coverage of the <code>viewChild()</code> signal query.</p>
<p>But notice that most of what we have learned here <strong>can also be applied to <em>all</em> other signal queries</strong>.</p>
<p>They all work in a very similar way.</p>
<p>Let's now move on to other types of queries.</p>
<h2 id="what-is-viewchildren">What is viewChildren()?</h2>
<p><code>viewChildren()</code> is a signal-based query used to retrieve multiple elements from the component's template, instead of just a single one like it's the case with<br>
<code>viewChild()</code>.</p>
<p>These elements can either be, like in the case of <code>viewChild</code>:</p>
<ul>
<li>ElementRef instances (plain HTML elements)</li>
<li>Angular component instances</li>
<li>directives linked to a component</li>
</ul>
<p>There are quite some neat use cases for <code>viewChildren()</code>, as we will see!</p>
<p>Let's start by learning the most common case, which involves querying a list of components from the template.</p>
<h2 id="query-components-with-viewchildren">Query components with <code>viewChildren()</code></h2>
<p>Here is a template with a list of <code>book</code> components:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
        &lt;div>
            &lt;book/>
            &lt;book/>
            &lt;book/>
            &lt;book/>
        &lt;/div>
    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>

  bookComponents <span class="token operator">=</span>
          <span class="token function">viewChildren</span><span class="token punctuation">(</span>BookComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
          <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">bookComponents</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>The viewChildren query will find all matching <code>&lt;book /&gt;</code> components in the template.</p>
<p>This code will print out to the console an array of 4 <code>BookComponent</code> instances, in the order that they are found in the template.</p>
<p>But what about querying based on template references, how does that work?</p>
<h2 id="using-viewchildren-to-find-multiple-matches-of-the-same-template-reference">Using viewChildren() to find multiple matches of the same template reference</h2>
<p>A little-known property of <code>viewChildren()</code> is that we can apply the <em>same template reference</em> in multiple elements, and <code>viewChildren()</code> will still work as expected.</p>
<p>For example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
        &lt;div>
            &lt;book #book>First Book&lt;/book>
            &lt;book #book>Second Book&lt;/book>
            &lt;book #book>Third Book&lt;/book>
        &lt;/div>
    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>

    books <span class="token operator">=</span> <span class="token generic-function"><span class="token function">viewChildren</span><span class="token generic class-name"><span class="token operator">&lt;</span>BookComponent<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token string">"book"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 

<span class="token punctuation">}</span> 
</code></pre></div>
<p>In this case, <code>viewChildren()</code> will return an array of 3 <code>&lt;book /&gt;</code> instances!</p>
<p>Notice that just because we are querying based on a template reference, we will still get back components, and <em>not</em> just plain HTML elements.</p>
<p><code>viewChildren()</code> will notice that the query based on a template reference matches components, so it will return components automatically instead of plain HTML elements.</p>
<p>So in that sense, this default behavior is slightly different than the default behavior of <code>viewChild()</code>.</p>
<h2 id="querying-plain-html-elements-with-viewchildren">Querying plain HTML elements with <code>viewChildren()</code></h2>
<p>Let's now see what happens if we apply instead the same template reference to several plain HTML elements, instead of components:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
        &lt;div>
            &lt;div #book>First Book&lt;/div>
            &lt;div #book>Second Book&lt;/div>
            &lt;div #book>Third Book&lt;/div>
        &lt;/div>
    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>

    books <span class="token operator">=</span> <span class="token function">viewChildren</span><span class="token punctuation">(</span><span class="token string">"book"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 

<span class="token punctuation">}</span> 
</code></pre></div>
<p>In this case, <code>viewChildren()</code> will return a signal that emits an array of <code>ElementRef</code> instances, matching the plain HTML elements.</p>
<p>So this all works exactly as expected.</p>
<p>But what if we want to query the HTML elements of a list of components, instead of the components themselves?</p>
<p>We can still do so in the following way:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
        &lt;div>
            &lt;book #book>First Book&lt;/book>
            &lt;div #book>Second Book&lt;/book>
            &lt;div #book>Third Book&lt;/book>
        &lt;/div>
    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>

    books <span class="token operator">=</span> <span class="token generic-function"><span class="token function">viewChildren</span><span class="token generic class-name"><span class="token operator">&lt;</span>BookComponent<span class="token operator">></span></span></span><span class="token punctuation">(</span>
    <span class="token string">"book"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
        read<span class="token operator">:</span> ElementRef
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 

<span class="token punctuation">}</span> 
</code></pre></div>
<p>By using the &quot;read&quot; parameter, we can specify what we want to query in the matching elements, instead of relying on defaults.</p>
<p>We can query by ElementRef, component, or any directive applied to the matching elements.</p>
<p>And with this, we have completed our coverage of regular template queries via <code>viewChild()</code> and <code>viewChildren()</code>.</p>
<p>Let's now move on to template queries related to content projection:<br>
<code>contentChild()</code> and <code>contentChildren()</code>.</p>
<h2 id="what-is-contentchild">What is contentChild()?</h2>
<p>Most of the template queries that you need to do will use <code>viewChild()</code> or<br>
<code>viewChildren()</code>.</p>
<p>But there are cases related to content projection that require something else.</p>
<p>If you are not familiar yet with content projection, you can read about it in detail in this guide: <a href="https://blog.angular-university.io/angular-ng-content/">Angular Content Projection: Complete Guide</a>.</p>
<p>But in case you are not familiar with it, let me give you a quick summary here.</p>
<p>Content projection is a powerful feature of the Angular framework that enables building highly configurable and reusable components.</p>
<p>Imagine that we would like to customize the <code>BookComponent</code> component by passing it a feature to be displayed in a book page, like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;book>
      &lt;div #feature>
      In depth guide to Angular
      &lt;/div>
    &lt;/book>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that we could potentially pass <em>any</em> HTML for the title, with icons, links, etc., and that would still work.</p>
<p>We can pass any HTML that we want and that will be used for the title.</p>
<p>And here is what the book component would look like:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div class="book">
      &lt;div class="features-container">
        &lt;ng-content>&lt;/ng-content>
      &lt;/div>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

  feature <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span><span class="token string">"feature"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Feature: "</span><span class="token punctuation">,</span> 
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">feature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>The book component is simply taking <em>all</em> the content passed to it and projecting it into the <code>ng-content</code> tag.</p>
<p>Again, for more details on how this works, have a look at this <a href="https://blog.angular-university.io/angular-ng-content/">guide</a>.</p>
<p>Now imagine that for some reason, the <code>&lt;book/&gt;</code> component needs to be able to query the content projected into it.</p>
<p>It's actually already trying to do so using the <code>viewChild()</code> signal query to access the feature element passed to it.</p>
<p>Will this work?...</p>
<p>You guessed it, it won't!</p>
<p>This is because the <code>viewChild()</code> signal query only works for elements that are <em>direct children</em> of the componen, meaning elements of it's own template.</p>
<p><code>viewChild()</code> will simply <em>not</em> work for elements that are projected into the component via <code>ng-content</code>.</p>
<p>But that is exactly where <code>contentChild()</code> comes in!</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div class="book">
      &lt;div class="features-container">
        &lt;ng-content>&lt;/ng-content>
      &lt;/div>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

  feature <span class="token operator">=</span> <span class="token function">contentChild</span><span class="token punctuation">(</span><span class="token string">"feature"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Feature: "</span><span class="token punctuation">,</span> 
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">feature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>This will now work as intended!</p>
<p>Also notice that to access the project elements, we didn't have to use the<br>
<code>AfterContentInit</code> lifecycle hook, like we used to do with the <code>@ContentChild</code> decorator.</p>
<p>Instead, a plain signal effect() was enough to get notified when the projected element was ready.</p>
<h2 id="what-is-the-difference-between-viewchild-and-contentchild">What is the difference between viewChild and contentChild?</h2>
<p>And so now we understand the difference between <code>viewChild()</code> and<br>
<code>contentChild()</code>:</p>
<ul>
<li><code>viewChild()</code> is used to query elements that are <em>direct children</em> of the component, and exist on the component's own private template</li>
<li><code>contentChild()</code> is used to query elements that are <em>projected into</em> the component via <code>ng-content</code>. Those project elements exist outside the template of the component using contentChild, in their parent component's templates.</li>
</ul>
<p>Other than that, they work exactly in the same way.</p>
<p>You can use <code>contentChild()</code> to query components, plain HTML elements, or directives in all the content projected via <code>ng-content</code>.</p>
<p>But just to drive this point home, here are a few more examples of how to use <code>contentChild()</code>.</p>
<h2 id="contentchild-and-component-queries">contentChild() and Component Queries</h2>
<p>Imagine that the parent component is trying to project a <code>&lt;feature /&gt;</code> component into the <code>BookComponent</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">,</span> FeatureComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;book>
      &lt;feature>
      In depth guide to Angular
      &lt;/feature>
    &lt;/book>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>You can also query components in the projected content like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div class="book">
      &lt;div class="features-container">
        &lt;ng-content>&lt;/ng-content>
      &lt;/div>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

  feature <span class="token operator">=</span> <span class="token function">contentChild</span><span class="token punctuation">(</span>FeatureComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Feature: "</span><span class="token punctuation">,</span> 
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">feature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, this works exactly in the same way as <code>viewChild()</code>, all the same rules, features, and defaults apply.</p>
<h2 id="using-read-on-contentchild">Using &quot;read&quot; on contentChild()</h2>
<p>We have even a &quot;read&quot; option for <code>contentChild()</code>, just like we had for <code>viewChild()</code>, that works in the exact same way:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div class="book">
      &lt;div class="features-container">
        &lt;ng-content>&lt;/ng-content>
      &lt;/div>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

  feature <span class="token operator">=</span> <span class="token function">contentChild</span><span class="token punctuation">(</span><span class="token string">"feature"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
    read<span class="token operator">:</span> ElementRef
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Feature: "</span><span class="token punctuation">,</span> 
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">feature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>This will return as the ElementRef of the queried element, instead of the component instance, in case that the matching element is a component.</p>
<h2 id="making-contentchild-to-be-required">Making contentChild() to be required</h2>
<p>And finally, we can also make <code>contentChild()</code> to be required, just like we did with <code>viewChild()</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  feature <span class="token operator">=</span> contentChild<span class="token punctuation">.</span><span class="token function">required</span><span class="token punctuation">(</span><span class="token string">"feature"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>As you can see, the API and the way of using <code>contentChild()</code> is 100% identical and consistent with <code>viewChild()</code>.</p>
<p>If you know one, you know the other.</p>
<h2 id="what-is-contentchildren">What is contentChildren()?</h2>
<p><code>contentChildren()</code> is the content projection equivalent of <code>viewChildren()</code>.</p>
<p>It allows us to query multiple elements projected into the component via<br>
<code>ng-content</code>, instead of just one like it's the case of <code>viewChildren()</code>.</p>
<p>As an example, let's consider this parent component, projecting multiple elements into the <code>BookComponent</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;book>
      &lt;div #title>Title 1&lt;/div>
      &lt;div #title>Title 2&lt;/div>
      &lt;div #title>Title 3&lt;/div>
    &lt;/book>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As we can see, we are projecting plain HTML title elements into the<br>
<code>BookComponent</code> via <code>ng-content</code>.</p>
<p>We can query these elements from inside <code>BookComponent</code> using<br>
<code>contentChildren()</code> like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">bookTitles <span class="token operator">=</span> <span class="token function">contentChildren</span><span class="token punctuation">(</span><span class="token string">"title"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>This will return a signal which emits as values a list of ElementRef instances of the queried elements.</p>
<p>But what if we were projecting components instead of plain HTML elements?</p>
<p>Here is an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">,</span> TitleComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;book>
      &lt;title>Title 1&lt;/title>
      &lt;title>Title 2&lt;/title>
      &lt;title>Title 3&lt;/title>
    &lt;/book>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>To retrieve the project <code>&lt;title /&gt;</code> components, we would do:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">bookTitles <span class="token operator">=</span> <span class="token function">contentChildren</span><span class="token punctuation">(</span>TitleComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>And of course, we could also query for directives applied to those elements by using the &quot;read&quot; option.</p>
<p>Here is how we would query for the ElementRef of the projected <code>&lt;title /&gt;</code> components:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">bookTitles <span class="token operator">=</span> <span class="token function">contentChildren</span><span class="token punctuation">(</span><span class="token string">"title"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  read<span class="token operator">:</span> ElementRef
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>This would work as usual with any other directive applied to the projected elements.</p>
<p>And with this, we have completed our full coverage of the signal queries available to us in Angular.</p>
<p>Let's then quickly summarize everything that we have learned, and wrap things up.</p>
<h2 id="summary">Summary</h2>
<p>In this extensive guide, we explored in depth <em>all</em> the signal queries available to us: <code>viewChild()</code>, <code>viewChildren()</code>, <code>contentChild()</code> and <code>contentChildren()</code>.</p>
<p>We saw the advantages that they bring us over their decorator-based counterparts:</p>
<ul>
<li>easier to understand and use</li>
<li>easy to integrate with other signals</li>
<li>usually don't require the need for lifecycle hooks</li>
</ul>
<p>These queries are a major step forward for the framework, and together with the rest of the signal-based APIs, they make Angular a breeze to work with.</p>
<p>The default behavior and configuration options of these queries is perfectly consistent, so if you know viewChild / viewChildren, you will automatically know contentChild / contentChildren.</p>
<p>And if you aren't familiar yet with the other <code>input()</code>, <code>output()</code>, and <code>model()</code> signal-based APIs, I would recommend you to check them out as well:</p>
<p><a href="https://blog.angular-university.io/angular-signal-components/">Angular Signal Components: input, output, model (Complete Guide)</a></p>
<p>Go ahead and try the new signal-based component authoring APIs out in your applications, and let me know in the comments below any questions you might have.</p>
<p>I would be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Signals Component API: input, output, model (Complete Guide)</title>
      <link>https://blog.angular-university.io/angular-signal-components/</link>
      <guid isPermaLink="false">6630fc8fd41ed50001ff7ae7</guid>
      <pubDate>Thu, 02 May 2024 07:15:40 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to Angular signal components, the new component authoring format.  This includes signal-based inputs, outputs, and two-way binding with model(). </description>
      <content:encoded><![CDATA[<p>With the rise of signals in the Angular ecosystem, Angular has now available a <strong>completely new way of authoring components</strong>, directives, and pipes.</p>
<p>This new authoring format is called Signal Components, and it's way simpler and more powerful than the traditional one.</p>
<p>Signal components are a completely new alternative to the traditional <code>@Input()</code> and <code>@Output()</code> decorators, and they also provide a new way of doing two-way binding.</p>
<p>They are now the <strong>recommended way to author new components in Angular</strong> going forward, and just to be clear they are ready to be used <em>today</em>.</p>
<p>This new signal-based authoring format is characterized by the absence of decorators, as well as by the absence of most lifecycle hooks, and by its deep integration with signals.</p>
<p>Signal components are way better than the old format, as you will learn in this post.</p>
<blockquote>
<p>To be able to benefit from Signal Components, you will need to upgrade to Angular 17.3 or beyond.</p>
</blockquote>
<p>In this guide, I will explain the <code>input</code>, <code>output</code>, and <code>model</code> component authoring primitives, and show how to use them to author signal-based Angular components.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>Signal inputs with <code>input()</code></li>
<li>Reading <code>input()</code> values</li>
<li>Optional inputs</li>
<li>Making an input to be required</li>
<li>Setting a custom public name: alias</li>
<li>Value transformation: transform</li>
<li>Deriving values from input signals</li>
<li>No more need for the OnChanges lifecycle hook</li>
<li>What is <code>output()</code>?</li>
<li>Alias on output()</li>
<li>output() RxJs interoperability using outputFromObservable()</li>
<li>output() RxJs interoperability using outputToObservable()</li>
<li>What is <code>model()</code>?</li>
<li>Two-Way Binding to a Signal Value</li>
<li>When to use model()?</li>
<li>Two-Way Binding to a Non-Signal Value</li>
<li>Responding to model changes</li>
<li>Using alias on model()</li>
<li>Making model() to be required</li>
<li>Summary</li>
</ul>
<p>To understand how Signal components work, you need to first understand the basics of signals in Angular.</p>
<p>So if you haven't done so already, I recommend that you read first this other guide: <a href="https://indepth.dev/posts/1487/angular-signals-the-complete-guide" target="_blank" rel="noopener">Angular Signals: The Complete Guide</a>.</p>
<p>Note that there are also new signal-based alternatives to view queries and content queries, but those will be covered in a separate guide:</p>
<p><a href="https://blog.angular-university.io/angular-viewchild-contentchild/">Angular Signal Queries: viewChild, contentChild, viewChildren, contentChildren (Complete Guide)</a></p>
<h2 id="signal-inputs-with-input">Signal inputs with <code>input()</code></h2>
<p>The <code>input()</code> API function is a direct replacement for the <code>@Input()</code> decorator.</p>
<p>This is the new signal-based way of defining component inputs in Angular.</p>
<p>But notice that with the arrival of <code>input()</code>, the <code>@Input()</code> decorator is <em>not</em> deprecated, it will still be supported for the foreseeable future.</p>
<p>With <code>input()</code>, the input values of an input property are exposed as a Signal.</p>
<p>The signal always holds the latest value of the input that is bound from the parent.</p>
<p>For example, here is how we create an input property <code>book</code> in a <code>BookComponent</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> input <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
 book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here we used <code>input()</code> to create an input field <code>book</code>.</p>
<p>The <code>input</code> function returns a read-only Signal of type <code>InputSignal&lt;Book&gt;</code>.</p>
<p>So <code>book</code> is <em>not</em> a plain <code>Book</code> object anymore, like it would be with the traditional <code>@Input()</code> decorator.</p>
<p>Instead, <code>book</code> now becomes a signal that holds <em>the latest value</em> of the input that is bound from the parent.</p>
<p>But even though we are now using a signal input, from the point of view of the parent component, nothing changes.</p>
<p>You can still send data from a parent component to the <code>BookComponent</code> via a<br>
<code>book</code> input property name, just like with the @Input() decorator:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[book]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>angularCoreDeepDiveBook<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">angularBook <span class="token operator">=</span> <span class="token punctuation">{</span>
  title<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
  synopsis<span class="token operator">:</span> <span class="token string">"A deep dive into Angular core concepts"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre></div>
<p>We passed the <code>angularCoreDeepDiveBook</code> book object to the <code>BookComponent</code> via the <code>book</code> property.</p>
<h2 id="reading-input-values">Reading <code>input()</code> values</h2>
<p>So from the point of view of the parent component, everything remains the same.</p>
<p>But what about the component itself, how can we get the input value?</p>
<p>To read the value, we need to call or invoke the <code>book</code> input signal, just like with any other signal in Angular:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">book</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The above invocation will return the latest value of the <code>book</code> signal, which contains the value of the <code>angularBook</code> object.</p>
<p>Notice that <strong>signals always have a value</strong>, so the return value of <code>book()</code> will either be undefined or a book object.</p>
<p>Let's now edit our component to display the title and synopsis of the book in its template:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> input <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that in the template, we invoked the <code>book()</code> signal and then accessed the <code>title</code> and <code>synopsis</code> properties.</p>
<p>We were careful to use the <code>?.</code> optional chaining operator because the <code>book</code> value can potentially be undefined.</p>
<p>This works, but it's potentially cumbersome.</p>
<p>What if we are sure and can give the guarantee that the <code>book</code> value will <em>never</em> be undefined?</p>
<p>That brings us to the two different types of signal inputs we can have in Angular:</p>
<ul>
<li>Optional inputs</li>
<li>Required inputs</li>
</ul>
<h2 id="optional-signal-inputs">Optional signal inputs</h2>
<p>By default, inputs created via <code>input()</code> are considered optional.</p>
<p>This means that we <em>don't</em> have to provide a value for the input when using the component from the parent component.</p>
<p>The example that we used above with the <code>BookComponent</code> was an optional input.</p>
<p>This means a couple of important things:</p>
<p>First, we can use the <code>BookComponent</code> without providing a value for the <code>book</code> input:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>Second of all, in this situation, the <code>book</code> signal will have its value as <code>undefined</code>.</p>
<p>If we don't want to have the default value of undefined, we can also pass an initial value to our optional <code>input()</code> like this:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">const</span> age <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token builtin">number</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The initial value of the <code>age</code> input signal will now become 0, instead of undefined.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">age</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 0</span>
</code></pre></div>
<h2 id="making-an-input-to-be-required">Making an input to be required</h2>
<p>There are some scenarios in which we want our input properties to be required, instead of optional. Here is how we do it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> input<span class="token punctuation">,</span> required <span class="token punctuation">}</span> 
<span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book().title }}&lt;/b>
    &lt;div>{{ book().synopsis }}&lt;/div>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>A couple of important things when we use <code>input.required()</code>:</p>
<ul>
<li>
<p>We can no longer provide an initial value to the input signal. The initial value will be the value assigned to the input.</p>
</li>
<li>
<p>We can't no longer omit the <code>book</code> property in the parent component:</p>
</li>
</ul>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>This will now throw a compilation error because the <code>book</code> input field is no longer optional!</p>
<p>To solve this, we need to pass the <code>book</code> property to the <code>BookComponent</code>.</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[book]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>angularBook<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>And so this covers the fundamentals of how optional and required inputs work.</p>
<p>Let's now talk about some common extra configuration options that you might need for your signal inputs.</p>
<h2 id="setting-an-input-property-alias">Setting an input property alias</h2>
<p>Most of the time, we want the name of our input property to be the same as the name of the input signal.</p>
<p>But sometimes, we might want the input property to have a different name.</p>
<p>This should be rarely needed, but it might be useful in some cases.</p>
<p>If you run into one of those situations, here is how you create an input alias both for optional and required inputs:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">input</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  alias<span class="token operator">:</span> <span class="token string">"bookInput"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

book <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  alias<span class="token operator">:</span> <span class="token string">"bookInput"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>And this is how you use the input alias in the parent component:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[bookInput]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>angularBook<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>Notice that if you try to use the input property name instead of the alias, like this:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[book]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>angularBook<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>It won't work, you will get an error:</p>
<blockquote>
<p>NG8002: Can't bind to 'book' since it isn't a known property of 'book'.</p>
</blockquote>
<h2 id="input-value-transformation-the-transform-function">Input value transformation: the transform function</h2>
<p>There are some rare situations where we might want to transform the input value before it is assigned to the input signal.</p>
<p>We can transform the raw data coming in from the parent component by using an input transform.</p>
<p>Here is how we can define input transforms, both for optional and required inputs:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">book <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  <span class="token function-variable function">transform</span><span class="token operator">:</span> <span class="token punctuation">(</span>value<span class="token operator">:</span> Book <span class="token operator">|</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>value<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

    value<span class="token punctuation">.</span>title <span class="token operator">+=</span> <span class="token string">" :TRANSFORMED"</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> value<span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

book <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token function">required</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token function-variable function">transform</span><span class="token operator">:</span> <span class="token punctuation">(</span>value<span class="token operator">:</span> Book <span class="token operator">|</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>value<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

    value<span class="token punctuation">.</span>title <span class="token operator">+=</span> <span class="token string">" :TRANSFORMED"</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> value<span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The value of the transform property should be a pure function, with no side effects.</p>
<p>Inside this function is where we write our value transformation logic, and we <em>must</em> return a value from the function.</p>
<h2 id="deriving-values-from-signal-inputs">Deriving values from signal inputs</h2>
<p>Since an <code>input()</code> is just a signal, we can do anything with it that we can do with any signal, including calculating a derived signal from it.</p>
<p>Here is how we can create a derived signal from an input signal using the computed() API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> input<span class="token punctuation">,</span> computed <span class="token punctuation">}</span> 
   <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
    &lt;div>{{ bookLength() }}&lt;/div>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  bookLength <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">book</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>title<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The <code>bookLength</code> is our derived signal from the <code>book</code> signal.</p>
<p>Whenever the <code>book</code> input signal value changes, then the <code>bookLength</code> signal will also be recalculated.</p>
<p>We could also apply an effect() on top of a book signal to monitor changes to it.</p>
<p>Remember, <strong>an input signal is just a read-only signal</strong>, there is nothing special about it. You can do with it all the usual operations that you can do with any other signal.</p>
<h2 id="no-more-need-for-the-onchanges-lifecycle-hook">No more need for the OnChanges lifecycle hook</h2>
<p>Let's talk about a hidden benefit of using signal inputs instead of the <code>@Input()</code> decorator.</p>
<p>Imagine that we would like to get notified when a component input changes. Traditionally, this was done using the <code>OnChanges</code> lifecycle hook:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> OnChanges <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token keyword">implements</span> <span class="token class-name">OnChanges</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> book<span class="token operator">:</span> Book<span class="token punctuation">;</span>

  <span class="token function">ngOnChanges</span><span class="token punctuation">(</span>changes<span class="token operator">:</span> SimpleChanges<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>changes<span class="token punctuation">[</span>book<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Book changed: "</span><span class="token punctuation">,</span> 
         changes<span class="token punctuation">.</span>book<span class="token punctuation">.</span>currentValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>But with the new signal-based component authoring format, we no longer need to use the <code>OnChanges</code> lifecycle hook.</p>
<p>Instead, we can use the <code>effect()</code> API to get notified whenever an input signal changes:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Book changed: "</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">book</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, no special lifecycle hook is required, just a plain effect() call will do the trick!</p>
<p>And this essentially covers everything that we need to know about component inputs.</p>
<p>Let's now talk about outputs, and cover also the less commonly used <code>model()</code> two-way binding API.</p>
<h2 id="angular-component-outputs-with-output">Angular component outputs with <code>output()</code></h2>
<p>The <code>output()</code> API is a direct replacement for the traditional <code>@Output()</code> decorator.</p>
<p>Notice that the <code>@Output</code> decorator is <em>not</em> deprecated, as it will still be supported for the foreseeable future.</p>
<p>But it would be weird to have inputs with <code>input()</code> and outputs with <code>@Output()</code>, right?</p>
<p>So Angular has added <code>output()</code> as a new way to define component outputs in Angular, in a way that is more type-safe and better integrated with RxJs than the traditional <code>@Output</code> and <code>EventEmitter</code> approach.</p>
<p>Here is how we can use the new <code>output()</code> API to define a component output in Angular:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> output <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
 deleteBook <span class="token operator">=</span> <span class="token generic-function"><span class="token function">output</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that the <code>output</code> function returns an <code>OutputEmitterRef</code>.</p>
<p>The <code>&lt;Book&gt;</code> generic type in <code>output&lt;Book&gt;()</code> indicates that this output will only emit values of type <code>Book</code>.</p>
<p>The parent component can then listen to the <code>deleteBook</code> output event using the usual event handling syntax:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">(deleteBook)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>deleteBookEvent($event)<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">deleteBookEvent</span><span class="token punctuation">(</span>book<span class="token operator">:</span> Book<span class="token punctuation">)</span> <span class="token punctuation">{</span>
 <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>book<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>So as you can see, from the point of view of the parent component, the use of <code>output()</code> is indistinguishable from the traditional <code>@Output()</code> decorator.</p>
<p>Let's now see how we can emit values using an <code>output()</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> output <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
    &lt;button (click)="onDelete()">Delete Book&lt;/button>
  &lt;/div></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  deleteBook <span class="token operator">=</span> <span class="token generic-function"><span class="token function">output</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">onDelete</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>deleteBook<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      title<span class="token operator">:</span> <span class="token string">"Angular Deep Dive"</span><span class="token punctuation">,</span>
      synopsis<span class="token operator">:</span> <span class="token string">"A deep dive into Angular core concepts"</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As we can see,the <code>onDelete</code> method will then emit a book object via the <code>deleteBook</code> output.</p>
<p>And this covers the basics for <code>output()</code>. Let's now cover the configuration options we have available as well as the new RxJs integration.</p>
<h2 id="setting-an-alias-on-an-output">Setting an alias on an output()</h2>
<p>Just like in the case of signal inputs, we can also define an alias for an <code>output()</code> like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">deleteBook <span class="token operator">=</span> <span class="token generic-function"><span class="token function">output</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  alias<span class="token operator">:</span> <span class="token string">"deleteBookOutput"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The parent component will then use <code>deleteBookOutput</code> to listen to the output event:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">(deleteBookOutput)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>deleteBookEvent($event)<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<h2 id="output-rxjs-interoperability-using-outputfromobservable">output() RxJs Interoperability using outputFromObservable()</h2>
<p>As we can see, <code>output()</code> is <em>not</em> signal-based, it's just more type-safe than the traditional <code>@Output()</code> decorator.</p>
<p>But besides that, one of the advantages is that it provides a <strong>much better interoperability with RxJs</strong>.</p>
<p>For example, we can very easily create an output signal that emits values from an observable.</p>
<p>We can do this by calling the <code>outputFromObservable</code> function:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> outputFromObservable <span class="token punctuation">}</span> 
   <span class="token keyword">from</span> <span class="token string">"@angular/core/rxjs-interop"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
  &lt;/div></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  deleteBook <span class="token operator">=</span> <span class="token generic-function"><span class="token function">outputFromObservable</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span>
    <span class="token keyword">of</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      title<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
      synopsis<span class="token operator">:</span> <span class="token string">"A deep dive into the core features of Angular."</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In the above example, we created an Observable that emits a book Object, just as an example.</p>
<p>Then we created an output signal <code>deleteBook</code> that emits as a component output the values emitted by the Observable.</p>
<h2 id="output-rxjs-interoperability-with-outputtoobservable">output() RxJs interoperability with outputToObservable()</h2>
<p>We can go the other way around and convert an output into an observable.</p>
<p>We do this by calling the <code>outputToObservable</code> function and passing a component output to it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span>
 outputToObservable<span class="token punctuation">,</span>
<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core/rxjs-interop"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>

 deleteBook <span class="token operator">=</span> <span class="token generic-function"><span class="token function">output</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

 deleteBookObservable$ <span class="token operator">=</span> 
   <span class="token function">outputToObservable</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>deleteBook<span class="token punctuation">)</span><span class="token punctuation">;</span>

 <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 <span class="token keyword">this</span><span class="token punctuation">.</span>deleteBookObservable$<span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span><span class="token punctuation">(</span>book<span class="token operator">:</span> Book<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
 <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Book emitted: "</span><span class="token punctuation">,</span> book<span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we have easily created a new observable <code>deleteBookObservable$</code> from the <code>deleteBook</code> output signal.</p>
<p>The values emitted by the Observable will be the same as the values emitted by the <code>deleteBook</code> output.</p>
<p>And with this, we have covered in detail how to define component outputs using the new <code>output()</code> API.</p>
<p>Let's now talk about another API that is strongly related to both <code>input()</code> and<br>
<code>output()</code>: the new <code>model()</code> API.</p>
<h2 id="what-is-the-model-api">What is the <code>model()</code> API?</h2>
<p>Besides <code>input()</code>and <code>output()</code>, Angular signal components also include a new API called <code>model()</code> for creating what is known as <em>model inputs</em>.</p>
<blockquote>
<p>A Model input is essentially a writeable input!</p>
</blockquote>
<p>Model inputs allow us to specify a two-way data binding contract between the parent component and the child component.</p>
<p>With <code>model()</code>, not only the parent component can pass data through it to child components, but child components can also emit data back to the parent component.</p>
<h2 id="two-way-data-binding-using-model">Two-way data binding using model()</h2>
<p>Here is how <code>model()</code> works.</p>
<p>We start by using it just like we would use a regular <code>input()</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"book"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div class="book-card">
    &lt;b>{{ book()?.title }}&lt;/b>
    &lt;div>{{ book()?.synopsis }}&lt;/div>
    &lt;button (click)="changeTitle()">
      Change title
    &lt;/button>
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
 </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">BookComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">model</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">changeTitle</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>book<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>book<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>book<span class="token punctuation">)</span> <span class="token keyword">return</span><span class="token punctuation">;</span>
      book<span class="token punctuation">.</span>title <span class="token operator">=</span> <span class="token string">"New title"</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> book<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>See that we created a Model signal by calling the <code>model</code> function, instead of<br>
<code>input()</code>.</p>
<p>So now, the <code>book</code> signal is a ModelSignal, instead of an InputSignal.</p>
<p>So what's the difference?</p>
<p>The main difference is that unlike with a normal input, the book input is now a writeable signal, as we can see on the <code>changeTitle</code> method.</p>
<p>You can think of it as a writeable input/output signal.</p>
<p>This means that we can now emit values to it from the child component!</p>
<p>The child <code>BookComponent</code> can both receive new values using <code>book</code>, but it can also emit new values for that signal.</p>
<p>So there is now a contract established between the child and the parent component, they are both using signals for direct two-way communication.</p>
<p>Here is how this works from the point of view of the parent component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"booklist"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book [(book)]="book" />
    &lt;/div>
    &lt;div>
      &lt;b>Parent&lt;/b> &lt;br />
      &lt;div>{{ book().title }}&lt;/div>
      &lt;div>{{ book().synopsis }}&lt;/div>

      &lt;button (click)="changeSynopis()">
          Change Synopsis
        &lt;/button>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">signal</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    title<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
    synopsis<span class="token operator">:</span> <span class="token string">"Deep dive to advanced features of Angular"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">changeSynopis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>book<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>book<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      book<span class="token punctuation">.</span>synopsis <span class="token operator">+=</span> <span class="token string">"Updated synopis!!"</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> book<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>So here is what is going on.</p>
<p>Here, we created a plain writeable signal called <code>book</code> in the <code>BookListComponent</code>.</p>
<p>We then passed the <code>book</code> signal to the <code>book</code> model input of the <code>BookComponent</code> using the <code>[()]</code> syntax, which is often called the &quot;banana-in-a-box&quot; syntax.</p>
<p>This essentially means that we have created a two-way binding.</p>
<p>We have created a bi-directional contract between the parent and the child component, where they both agree to share data by emitting values via a shared model input.</p>
<p>So when the <code>changeSynopis</code> method is called in the <code>BookListComponent</code>, it will emit a new value to the <code>book</code> model input of the <code>BookComponent</code>.</p>
<p>And the other way around is also true: when the <code>changeTitle</code> method is called in the <code>BookComponent</code>, it will emit a new value to the <code>book</code> signal of the<br>
<code>BookListComponent</code>.</p>
<h2 id="when-to-use-model">When to use model()?</h2>
<p>So in a nutshell, <code>model()</code> is a two-way communication mechanism that is implemented by a writeable signal that is shared between the parent and the child component.</p>
<p>This could be useful for certain situations.</p>
<p>For example, imagine a date picker component with a main input <code>value</code>.</p>
<p>We can see how the value property would benefit from two-way binding. The parent wants to set the initial value, but also receive new values back.</p>
<p>In general though, unless we have a very specific reason for doing so, we should prefer the use of regular inputs and outputs, as they are more explicit and easier to understand.</p>
<p>The use of <code>model</code> can easily degenerate in code that is potentially hard to understand and debug.</p>
<p>Imagine that you pass a model input through several levels of nesting: it would be hard to know from where a certain value is coming from during debugging.</p>
<p>So my recommendation is, to use <code>model()</code> sparingly, if at all, and only when you have a very specific reason for doing so.</p>
<p>So don't feel forced to use <code>model()</code> just because it's new and shiny.</p>
<p>And don't fear missing out on something if you don't use <code>model()</code> often, or even at all.</p>
<p>Not every feature in a framework will have the same frequency of use, and that's perfectly fine.</p>
<h1 id="two-way-binding-to-a-non-signal-value">Two-Way Binding to a Non-Signal Value</h1>
<p>The main use case for model inputs is two-way data binding via a writeable signal.</p>
<p>But it's also possible to pass to a model input a plain non-signal value as well.</p>
<p>Let's edit the <code>BookListComponent</code> to use a non-signal input value:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"booklist"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book [(book)]="book">&lt;/book>
    &lt;/div>
    &lt;div>
      &lt;b>Parent&lt;/b> &lt;br />
      &lt;div>{{ book.title }}&lt;/div>
      &lt;i>{{ book.synopsis }}&lt;/i
      >&lt;br />

      &lt;button (click)="changeSynopis()">
          Change Synopsis
        &lt;/button>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> <span class="token punctuation">{</span>
    title<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
    synopsis<span class="token operator">:</span> <span class="token string">"Deep dive into advanced Angular features"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>

  <span class="token function">changeSynopis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>book<span class="token punctuation">.</span>synopsis <span class="token operator">+=</span> <span class="token string">"!"</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>See that the <code>book</code> class field is now a plain non-signal value!</p>
<p>Yet, it is still two-way data bound to the <code>book</code> input of the <code>BookComponent</code>.</p>
<p>Any updates that the parent component does will be reflected in the child component.</p>
<p>Likewise, any updates that the child component does to the <code>book</code> input model will be reflected in the parent component <code>book</code> property.</p>
<h2 id="responding-to-model-changes">Responding to model() changes</h2>
<p>Notice that we can also define an event handler that will be triggered whenever a model input emits a new value.</p>
<p>We can subscribe to model changes in the parent component by subscribing to the <code>bookChange</code> event like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"booklist"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;book [book]="book" 
            (bookChange)="bookChangeEvent($event)"/>
    &lt;/div>
    &lt;div>
      &lt;b>Parent&lt;/b> &lt;br />
      &lt;div>{{ book.title }}&lt;/div>
      &lt;i>{{ book.synopsis }}&lt;/i
      >&lt;br />
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  styles<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BookComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">BookListComponent</span> <span class="token punctuation">{</span>
  book <span class="token operator">=</span> <span class="token punctuation">{</span>
    title<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
    synopsis<span class="token operator">:</span> <span class="token string">"Deep dive into advanced Angular features"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>

  <span class="token function">bookChangeEvent</span><span class="token punctuation">(</span>book<span class="token operator">:</span> Book<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Book changed"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the event that we want to subscribe to follows a particular naming convention:</p>
<p>It's just the name of the model input <code>book</code>, followed by the suffix <code>Change</code>.</p>
<p>Notice that this naming convention is not specific to model inputs only, this is a general convention that is always available in bi-directional data binding scenarios.</p>
<p>Anywhere where you can apply the <code>[()]</code> syntax, you can also subscribe to the corresponding <code>Change</code> event.</p>
<h2 id="using-alias-on-model">Using alias on model()</h2>
<p>Just like in the case of inputs and outputs, we can set an alias to our model input as well:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">book <span class="token operator">=</span> <span class="token generic-function"><span class="token function">model</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span>
  <span class="token punctuation">{</span>
    title<span class="token operator">:</span> <span class="token string">"The Avengers"</span><span class="token punctuation">,</span>
    synopsis<span class="token operator">:</span> <span class="token string">"Loki is back to take over the world!"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span>
    alias<span class="token operator">:</span> <span class="token string">"bookInput"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Here is how we can bind to the book model input from the parent component:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[(bookInput)]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>book<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>  
</code></pre></div>
<h2 id="making-model-to-be-required">Making model to be required</h2>
<p>Just like in the case of inputs and outputs, we can also make the <code>model</code> to be required:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">book <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span>Book<span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>Now the parent component must pass a value to the <code>book</code> input of the <code>BookComponent</code>.</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>book</span> <span class="token attr-name">[(book)]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>book<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>Also, when we use <code>required</code> we do not pass an initial value to the <code>model</code> function call because a value must be supplied by the parent.</p>
<h2 id="summary">Summary</h2>
<p>In this guide, we have explored in detail the new <code>input()</code>, <code>output()</code>, and <code>model()</code> signal-based component authoring primitives.</p>
<p>As you can see, the new primitives are way cleaner than their traditional counterparts <code>@Input()</code>, <code>@Output()</code>, and <code>[(ngModel)]</code>.</p>
<p>They are less verbose, have a cleaner syntax, and reduce a lot the need for lifecycle hooks.</p>
<p>We now have all the flexibility and power of signals at our disposal when authoring our Angular components.</p>
<p>So go ahead and try out the new component authoring primitives, and let me know in the comments below of any questions you might have.</p>
<p>I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Performance Tuning: Complete Guide To Bundle Size Optimization</title>
      <link>https://blog.angular-university.io/angular-performance-tuning/</link>
      <guid isPermaLink="false">65d710b1876110000149e821</guid>
      <pubDate>Thu, 22 Feb 2024 14:43:38 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>Learn everything you need to know about Angular performance tuning: how to generate a bundle performance profile, and how to split up your application into smaller chunks via standalone lazy-loading and partial template loading.</description>
      <content:encoded><![CDATA[<p>If you ever run into a situation where your Angular application is taking too long to load, then this is the right post for you.</p>
<p>We are going to show you how to tackle this problem in a <strong>systematic, evidence-based approach</strong>.</p>
<p>We will first learn how to generate a performance profile for your bundle, to help identify the major performance culprits in your application.</p>
<p>From there, we are going to learn a couple of different ways to split up your application into smaller chunks, using the very latest performance features of Angular:</p>
<ul>
<li>standalone lazy-loading</li>
<li>partial template loading</li>
</ul>
<p>So without further let's get started with this Angular Performance Tuning deep dive!</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>What type of metrics should you collect?</li>
<li>Setting up the source map explorer package</li>
<li>Make your application fully lazy-loaded in a simplified way using standalone components</li>
<li>Partial template loading with @defer</li>
<li>The bottom line</li>
</ul>
<p>If you prefer to learn this content in video format, here is the video version of this post:</p>
<p><a href="https://www.youtube.com/watch?v=d5eIU5PEH8A" target="_blank" rel="noopener">Angular Performance Tuning Crash Course</a></p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/d5eIU5PEH8A?si=pYDL_4C5Wk8CKSLX" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<h2 id="what-type-of-metrics-should-you-collect">What type of metrics should you collect?</h2>
<p>Let's start with the most important first!</p>
<p>The worst thing that we can do when trying to optimize your application is to fly blind, and base ourselves on gut feelings and trial and error.</p>
<p>The first thing that we need to do is to collect some data, some metrics.</p>
<p>And for that, we are going to use the source map explorer package.</p>
<p>So your first step should always be to generate some sort of bundle profile report.</p>
<p>This is a disk space usage visual report, that tells you what libraries and Angular components are taking the most space in your Javascript bundle.</p>
<p>This will allow you to know what parts of your application are taking the most space. This is essential.</p>
<p>In order to collect this type of metrics, you will need the following profiling tool.</p>
<h2 id="setting-up-the-source-map-explorer-package">Setting up the source map explorer package</h2>
<p>The first thing that we should do is to install the following package in our codebase:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">npm install -g source-map-explorer
</code></pre></div>
<p>So once you have the package, you now need to use it to generate a report.</p>
<p>Here is the npm script that I usually use to generate my bundle report:</p>
<div class="code-block"><span class="code-lang">json</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-json"><code class="language-json"><span class="token punctuation">{</span>
    ...
  <span class="token property">"scripts"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    ...
    <span class="token property">"bundle-report"</span><span class="token operator">:</span> 
       "ng build --configuration production  
       --source-map &amp;&amp; 
       source-map-explorer dist/browser<span class="token comment">/*.js"
  },
}
</span></code></pre></div>
<p>This npm script report works in two parts:</p>
<ul>
<li>
<p>First, we need to do a production build of our application. So we are going to run <code>ng build --configuration production</code></p>
</li>
<li>
<p>once the uncompressed bundles are generated in your local file system, we are going to run the source-map-explorer package to generate a report.</p>
</li>
</ul>
<p>I recommend that you add a similar npm script to your project so that you can easily generate a bundle space usage report at any time that you want.</p>
<p>So once you open the report, you are going to see something like this:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-performance-tuning/angular-performance-tuning-1.jpeg" alt="Angular performance tuning of an application bundle" loading="lazy" decoding="async"></p>
<p>Don't get scared by these bundle sizes, the actual main production bundle is much smaller than this. Remember that these bundles are uncompressed.</p>
<p>Once you have this report, you can start identifying components and libraries that you can lazy load into a separate bundle.</p>
<p>Look for heavy dependencies that are rarely used, like PDF-generation libraries, chart libraries, etc.</p>
<p>These tend to be used rarely by the user, so they are ideal candidates for code splitting.</p>
<h2 id="make-your-application-fully-lazy-loaded">Make your application fully lazy-loaded</h2>
<p>Now you know what parts of your application take up the most space, so the next step is to make your application as lazy loaded as possible.</p>
<p>Ideally, every single screen of your application should be loaded in a separate bundle.</p>
<p>This is what I like to call a fully lazy-loaded application. But how do you make your application fully lazy-loaded?</p>
<p>The best way that you have available right now is to leverage the simplified lazy-loading features of standalone components.</p>
<p>So let me show you how simple it is to take a route of your router and make it lazy-loaded using Standalone components.</p>
<p>Here is a route with a screen that is currently <em>not</em> lazy-loaded:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token operator">...</span>
<span class="token keyword">export</span> <span class="token keyword">const</span> routes<span class="token operator">:</span> Routes <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">'courses/:courseUrl'</span><span class="token punctuation">,</span>
    component<span class="token operator">:</span> WatchCourseComponent
  <span class="token punctuation">}</span>
<span class="token punctuation">]</span>
<span class="token operator">...</span>
</code></pre></div>
<p>Notice that if you were using NgModule components, making this screen lazy-loaded would be quite a chore.</p>
<p>But luckily, this application is already migrated to standalone components!</p>
<p>So all we have to do to make this screen lazy-loaded is to switch the use of component to loadComponent, like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">'courses/:courseUrl'</span><span class="token punctuation">,</span>
    <span class="token function-variable function">loadComponent</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> 
      <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">'./watch-course/watch-course.component'</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>mod <span class="token operator">=></span> mod<span class="token punctuation">.</span>WatchCourseComponent<span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span>
</code></pre></div>
<p>And it's that simple!</p>
<p>Now this route is lazy-loaded, and the WatchCourseComponent and <em>all its dependencies</em> are off the main bundle.</p>
<p>So if this screen needed a heavy dependency like a PDF or chart library, now all those heavyweight dependencies are now off your main application bundle, and will be loaded only if necessary.</p>
<p>Remember, this only worked because the WatchCourseComponent is a standalone component.</p>
<p>If you are looking to learn more about standalone components and how to migrate to them, check out this in-depth guide that I wrote:</p>
<p><a href="https://blog.angular-university.io/angular-standalone-components/">Angular Standalone Components: The Complete Guide</a></p>
<p>You can now go back to your routing configuration, apply loadComponent everywhere, and you will have a fully lazy-loaded application where every single container screen has its own separate bundle.</p>
<p>Your main bundle should now contain the Angular framework and very little else, and hardly any heavy third-party dependencies.</p>
<p>This should already be enough to improve a lot the performance of your application, but we can go even further.</p>
<h2 id="partial-template-loading-with-defer">Partial template loading with @defer</h2>
<p>Now let's go ahead and let's introduce another performance optimization technique, which is similar to lazy loading.</p>
<p>So going back here to our codebase, we are already lazy loading this component, right?</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">'courses/:courseUrl'</span><span class="token punctuation">,</span>
    <span class="token function-variable function">loadComponent</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> 
      <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">'./watch-course/watch-course.component'</span><span class="token punctuation">)</span>
       <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>mod <span class="token operator">=></span> mod<span class="token punctuation">.</span>WatchCourseComponent<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

</code></pre></div>
<p>But now, imagine that this component <code>WatchCourseComponent</code> is still fairly large.</p>
<p>This component is a course player that supports different types of lessons:</p>
<ul>
<li>audio lessons</li>
<li>digital downloads</li>
<li>assessments, etc.</li>
</ul>
<p>And that is all part of the watch course screen.</p>
<p>But now imagine that a certain course only has video lessons.</p>
<p>So it <em>doesn't</em> have audio lessons, etc.</p>
<p>Then in that case loading the code for the audio lesson would be unnecessary and premature.</p>
<p>Ideally, we should only load the code for the audio lesson whenever the user actually clicks on an audio lesson, and not before.</p>
<p>This way, we avoid loading code that we might never use for that user session!</p>
<p>But the component as it stands right now will either load fully or not at all.</p>
<p>So what we need is some sort of partial template loading, that would allow us to load parts of a screen only when and if needed.</p>
<p>And we can do just that, using the powerful @defer feature of Angular:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer(when lesson.type == 'audio') { 

  @if(lesson.type == 'audio') {

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>audio-player</span> <span class="token attr-name">[lesson]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lesson<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>

  } 
}
</code></pre></div>
<p>The way that this works is that <code>defer</code> is going to make anything inside the defer block to get loaded on a separate bundle, much like the router-based lazy loading mechanism.</p>
<p>The <code>defer</code> block is going to make the code inside it lazy-loaded, and the <code>if</code> block is going to conditionally show or hide the audio player. The <code>defer</code> condition <code>@defer(when lesson.type == 'audio')</code> is going to make the audio player lazy-loaded only if the lesson is of type audio.</p>
<p>The result is that the code for the audio player is no longer part of the same bundle as its parent component the WatchCourseComponent.</p>
<p>Now with @defer, the code for the audio player will only get loaded if we navigate to an audio lesson.</p>
<p>The new Angular @defer functionality is very powerful, to learn more about it in detail, check out this in-depth guide that I wrote:</p>
<p><a href="https://blog.angular-university.io/angular-defer/">Angular @defer: The Complete Guide</a></p>
<h2 id="the-bottom-line">The bottom line</h2>
<p>So in summary, this is how you can do the performance tuning of your Angular application:</p>
<ul>
<li>Step 1: always make sure that you create some sort of a report that allows you to see what is taking up space in your application. The source-map-explorer package is a great tool for this.</li>
<li>Step 2: I recommend that you upgrade to Standalone components, and leverage the simplified lazy-loading feature loadComponent. With it, it's super easy to make every single screen of your application lazy-loaded.</li>
<li>Step 3: If you still have components that are too large, use @defer to do partial template loading inside your heavier components.</li>
</ul>
<p>If you iteratively follow these steps and keep generating bundle reports to confirm your progress and identify new bottlenecks, you will be able to make your application as lean as possible.</p>
<p>And remember, if you prefer to see all this in action in video format, here is the video version of this post showing how to optimize a real production application:</p>
<p><a href="https://www.youtube.com/watch?v=d5eIU5PEH8A" target="_blank" rel="noopener">Angular Performance Tuning Crash Course</a></p>
<p>Let me know in the comments if you have any questions or comments, I would love to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular 17.2 Is Out: What&#39;s New?</title>
      <link>https://blog.angular-university.io/angular-17-2-release/</link>
      <guid isPermaLink="false">65ce4c472ead4a000190d59d</guid>
      <pubDate>Fri, 16 Feb 2024 15:25:58 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>A complete guide to the brand new Angular 17.2 features, including: the new signal-based view queries viewChild, viewChildren, contentChild, and contentChildren, as well the new model() two-way binding mechanism.</description>
      <content:encoded><![CDATA[<p>In this blog post, we're going to learn about all the brand-new features introduced in the latest Angular 17.2 release.</p>
<p>We're going to be learning about the new <code>viewChild</code>, <code>viewChildren</code>, <code>contentChild</code>, and <code>contentChildren</code> signal-based alternatives to the decorators of the same name.</p>
<p>Let's learn why these decorators make the existing lifecycle hooks<br>
<code>AfterContentInit</code> and <code>AfterViewInit</code> no longer necessary.</p>
<p>We are also going to be covering a new <code>model()</code> API that will allow us to do two-way data binding with a signal-based approach.</p>
<p>So without further ado, let's dive right into the Angular 17.2 release!</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<ul>
<li>viewChild and viewChildren Signal-based Queries</li>
<li>contentChild and contentChildren Signal-based Queries</li>
<li>Two-way data binding model() API</li>
<li>Summary</li>
</ul>
<p>If you would like to learn about this release in video format, check out this video on the Angular University YouTube channel:</p>
<p><a href="https://www.youtube.com/watch?v=abUBuWVwK14" target="_blank" rel="noopener">Angular 17.2: SIGNAL COMPONENTS One Step Closer</a>:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/abUBuWVwK14?si=kfAUSeEMCwVhfFU6" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<p>Check out also the release post on the Angular Blog concerning the <a href="https://blog.angular.io/angular-v17-2-is-now-available-596cbe96242d" target="_blank" rel="noopener">Angular 17.2 release</a>.</p>
<h2 id="viewchild-signal-based-queries">viewChild Signal-based Queries</h2>
<p>Let's start by talking about the new alternative to the <code>@ViewChild</code> decorator.</p>
<p>As you know, the existing @ViewChild decorator allows you to grab a reference to a child element in your template:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"signals-demo"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;p>Parent counter {{ parentCounter }}&lt;/p>

    &lt;signal-counter [(count)]="parentCounter" />
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CounterComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">SignalsDemoComponent</span> 
   <span class="token keyword">implements</span> <span class="token class-name">AfterViewInit</span> <span class="token punctuation">{</span>
  parentCounter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">ViewChild</span></span><span class="token punctuation">(</span>SignalCounter<span class="token punctuation">)</span>
  counter<span class="token operator">:</span> SignalCounter<span class="token punctuation">;</span>

  <span class="token function">ngAfterViewInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>
    <span class="token string">"counter component:"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In this example, we are using a SignalCounter component in our template, and we want a reference to it here in our component.</p>
<p>Before Angular 17.2, we would create a @ViewChild query:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token decorator"><span class="token at operator">@</span><span class="token function">ViewChild</span></span><span class="token punctuation">(</span>SignalCounter<span class="token punctuation">)</span>
  counter<span class="token operator">:</span> SignalCounter<span class="token punctuation">;</span>
</code></pre></div>
<p>But now in Angular 17.2, we now have a signal-based alternative!</p>
<p>Let's remove the use of the <code>@ViewChild</code> decorator and the AfterViewInit lifecycle hook.</p>
<p>This lifecycle hook should normally no longer be necessary:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"signals-demo"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;p>Parent counter 
      {{ parentCounter }}&lt;/p>

    &lt;signal-counter #counter 
       [(count)]="parentCounter" />
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CounterComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">SignalsDemoComponent</span> <span class="token punctuation">{</span>

  parentCounter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

  counter <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span>CounterComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"counter component:"</span><span class="token punctuation">,</span> 
         <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This works in the same way, but as you can see, the new API looks much simpler.</p>
<p>We can also see that the use of the AfterViewInit lifecycle hook has been replaced by the use of a simple signal <code>effect()</code>.</p>
<p>Notice that the counter signal is now a signal of type Signal of CounterComponent.</p>
<p>This is just like any other regular Angular signal.</p>
<p>You can use anything in the Signals API to interact with it.</p>
<p>You can use the computed API to compute derived signals, and you can also use effects, as we have done here, to be notified when new values are emitted.</p>
<p>Now, you are probably wondering about all the typical options of the ViewChild decorator.</p>
<p>Well, these are also present in its signal-based alternative.</p>
<p>You have an options object that you can pass in. You can pass in the &quot;read&quot; property, just like the standard ViewChild decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">counter <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span>CounterComponent<span class="token punctuation">,</span> <span class="token punctuation">{</span>
  read<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>You can also query the view using a template variable. We have a <code>#counter</code> template variable. We can pass in the name of the variable:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">counter <span class="token operator">=</span> <span class="token function">viewChild</span><span class="token punctuation">(</span><span class="token string">"counter"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>And this would give us the same result.</p>
<p>If we want to make this <code>viewChild</code> property required, then you can do so using<br>
<code>viewChild.required</code>.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">counter <span class="token operator">=</span> viewChild<span class="token punctuation">.</span><span class="token function">required</span><span class="token punctuation">(</span><span class="token string">"counter"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<h2 id="the-viewchildren-signal-based-api">The viewChildren signal-based API</h2>
<p>Let's cover one more template query, the viewChildren query.</p>
<p>Let's say we have a component that uses multiple child components of the same type on its template.</p>
<p>We can query all the children in one go using the new viewChildren query:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"signals-demo"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;p>Parent counter {{ parentCounter }}&lt;/p>

    &lt;signal-counter [(count)] />
    &lt;signal-counter [(count)] />
    &lt;signal-counter [(count)] />
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CounterComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">SignalsDemoComponent</span> <span class="token punctuation">{</span>
  parentCounter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

  counters <span class="token operator">=</span> <span class="token function">viewChildren</span><span class="token punctuation">(</span>CounterComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"counters component:"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counters</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Again, notice that we don't need a lifecycle hook anymore, a simple effect will do.</p>
<h2 id="the-contentchild-and-contentchildren-queries">The contentChild and ContentChildren queries</h2>
<p>There are also new signal-based alternatives to the existing @ContentChild and @ContentChildren decorators, that work in the exact same way as explained for @ViewChild and @ViewChildren.</p>
<h2 id="the-model-two-way-binding-api">The model() two-way binding API</h2>
<p>Let's now focus on the new Model API for doing bidirectional data binding with a signal-based approach.</p>
<p>If you remember the traditional bi-directional data binding ngModel-based syntax,</p>
<p>I'm talking about the &quot;bananas in a box&quot; <code>[()]</code> syntax with the square brackets outside and the round brackets inside.</p>
<p>This can now be done also with a signal-based approach using the new <code>model</code> API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"signal-counter"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;div>Counter value: {{ count() }}&lt;/div>
      &lt;button (click)="onIncrement()">Increment&lt;/button>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  count <span class="token operator">=</span> <span class="token function">model</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">onIncrement</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">=></span> val <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we are just receiving a signal, which is the counter itself.</p>
<p>And whenever we click on the button, we increment the value of the counter.</p>
<p>If we check the type of this <code>count</code> variable, we can see that this is a<br>
<code>ModelSignal&lt;number&gt;</code>.</p>
<p>This is a special type of Writable signal, that allows us to do bi-directional data-binding from the point of view of the parent component.</p>
<p>So, if I go back to the parent component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"signals-demo"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;p>Parent counter {{ parentCounter }}&lt;/p>

    &lt;signal-counter [(count)]="parentCounter" />
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CounterComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">SignalsDemoComponent</span> <span class="token punctuation">{</span>
  parentCounter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We can see that we now are applying the two-way binding <code>[()]</code> syntax to the count property:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>signal-counter</span> <span class="token attr-name">[(count)]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>parentCounter<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>The <code>parentCounter</code> variable in now kept in sync with the counter variable from inside the <code>SignalCounter</code> automatically.</p>
<p>Remember that the binding goes two ways. So, if I initialize <code>parentCounter</code> with 100, then the <code>counter</code> value inside the <code>SignalCounter</code> is going to be initialized<br>
with the value of 100.</p>
<p>Then, if we start incrementing, the values start being incremented one by one, starting at the value of 100, 101, and 102, as expected.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to my newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>Signals</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>So these are the new APIs that we have available in Angular 17.2! These are going to make building signal-based components much easier.</p>
<p>Let me know if you have questions or comments in the comments section below.</p>
<p>I would be happy to help, cheers everyone.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular innerHTML and DomSanitizer: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-innerhtml/</link>
      <guid isPermaLink="false">65cb128e229cd200019be000</guid>
      <pubDate>Tue, 13 Feb 2024 09:17:26 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>A complete guide on how to use innerHTML and the DomSanitizer service in Angular for direct HTML injection, including the design and implementation of a reusable SafeHtml pipe that simplifies the whole process.
</description>
      <content:encoded><![CDATA[<p>There are a few common situations when developing a web application where we would like to <strong>apply some custom HTML directly to the page</strong>.</p>
<p>A typical case is for example when using a rich-text editor: let's say that we would like to display some HTML that we have saved on the database.</p>
<p>This sounds simple enough, but the reality is that the typical security features of a framework like Angular will make this task a bit more challenging than it sounds.</p>
<p>If you try to use the DOM innerHTML feature in an Angular application to apply some HTML to the page, <strong>this will not work as expected, the inline styles will be removed for example</strong>!</p>
<p>So in this guide, we will discuss some of the Angular built-in security measures that prevent this type of direct code injection, learn why they are in place, and show how we can still safely inject HTML content into the DOM if we really need to.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>Understanding innerHTML in Angular</li>
<li>The Problem with Direct innerHTML Use</li>
<li>Security Implications of Unescaped HTML</li>
<li>Angular's Sanitization and Security Measures</li>
<li>Bypassing Angular's Escaping using DomSanitizer (With Caution)</li>
<li>SafeHtml Pipe: A Safe Way to Inject HTML</li>
</ul>
<h2 id="understanding-innerhtml-in-angular">Understanding innerHTML in Angular</h2>
<p>The <code>innerHTML</code> DOM property allows developers to dynamically inject HTML content into the DOM in general.</p>
<p>Notice that <code>innerHTML</code> is <em>not</em> a specific Angular directive or anything, this is standard DOM functionality.</p>
<p>So let's assume that you are working on an Angular project, and you want to inject some HTML content into the DOM.</p>
<p>Your first instinct would be to use the <code>innerHTML</code> property to try to achieve this:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">[innerHTML]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>htmlContent<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
</code></pre></div>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
  htmlContent <span class="token operator">=</span> <span class="token string">"&lt;h1 style="</span>color<span class="token operator">:</span>red<span class="token string">">Hello World&lt;/h1>"</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The problem here is that Angular is <em>not</em> going to render this properly. The h1 tag will be rendered, but any inline styles typically applied in a rich text editor will be sanitized.</p>
<p>So the h1 tag will be displayed, but not in the color red.</p>
<p>And this is <em>not</em> what we were looking for!</p>
<p>So what is going on here?</p>
<h2 id="the-problem-with-direct-innerhtml-use-in-angular">The Problem with Direct innerHTML use in Angular</h2>
<p>The reason why this doesn't work out of the box is due to the Angular built-in code injection defenses, also known as XSS defenses or Cross-Site Scripting defenses.</p>
<p>By default, Angular is going to assume that any text that we pass to the template is unsafe, and it will escape it properly according to the context where we are using the text.</p>
<p>This might seem surprising the first time that you see it, but it's actually a good thing.</p>
<p>This escaping mechanism protects our application from many different types of script injection security attacks.</p>
<p>It's great to have all these defenses in place, but sometimes there are good reasons to want to bypass them in certain cases, like in the case of our rich-text editor example.</p>
<h2 id="bypassing-angular-escaping-with-domsanitizer-with-caution">Bypassing Angular Escaping with DomSanitizer (With Caution)</h2>
<p>The <code>DomSanitizer</code> service in Angular provides various methods to bypass security checks for trusted values.</p>
<p>Here's how you can use it:</p>
<ol>
<li>
<p>Import the <code>DomSanitizer</code> service: Import DomSanitizer from the <code>@angular/platform-browser</code> package in the component where you need to bypass escaping.</p>
</li>
<li>
<p>Inject <code>DomSanitizer</code> into your component's constructor: Add <code>DomSanitizer</code> to the component's constructor to make it available for use within the component.</p>
</li>
<li>
<p>Use the appropriate sanitization method, depending on the type of code that you need to inject:</p>
</li>
</ol>
<ul>
<li><code>bypassSecurityTrustHtml</code> for HTML.</li>
<li><code>bypassSecurityTrustStyle</code> for styles.</li>
<li><code>bypassSecurityTrustScript</code> for script URLs.</li>
<li><code>bypassSecurityTrustUrl</code> for URL/resource URLs.</li>
<li><code>bypassSecurityTrustResourceUrl</code> for resource URLs like iframe sources.</li>
</ul>
<p>Here is a complete example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-unsafe-component"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;div [innerHTML]="trustedHtml">&lt;/div></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">UnsafeComponent</span> <span class="token punctuation">{</span>
  trustedHtml<span class="token operator">:</span> <span class="token builtin">any</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token keyword">private</span> sanitizer<span class="token operator">:</span> DomSanitizer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> unsafeHtml <span class="token operator">=</span> <span class="token string">"&lt;h1>Hello World!&lt;/h1>"</span><span class="token punctuation">;</span>

    <span class="token comment">// Bypassing Angular's HTML sanitizer</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>trustedHtml <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>sanitizer
      <span class="token punctuation">.</span><span class="token function">bypassSecurityTrustHtml</span><span class="token punctuation">(</span>sanitizedHtml<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>And this will now work as expected!</p>
<p>What we are doing here is telling Angular:</p>
<blockquote>
<p>I'm sure that this text is safe, so you can skip the usual security measures.</p>
</blockquote>
<p>It's important to note that when bypassing Angular's escaping, you take on the responsibility of ensuring that the content is actually safe to render as HTML.</p>
<p>As you can see, this process works, but it can be quite cumbersome...</p>
<p>So here is a way to make it much more convenient.</p>
<h2 id="safehtml-pipe-a-more-convenient-way-to-inject-html-in-an-angular-application">SafeHtml Pipe: A More Convenient Way to Inject HTML in an Angular Application</h2>
<p>Let's then create a custom pipe that will sanitize HTML content passed to it.</p>
<p>It will return the sanitized HTML content to the caller to be injected into the DOM.</p>
<p>This pipe will internally use the <code>DomSanitizer</code>, so that we don't have to use it directly in several places of our application:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Pipe</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token operator">:</span> <span class="token string">"safeHtml"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">SafeHtmlPipe</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token keyword">private</span> sanitizer<span class="token operator">:</span> DomSanitizer<span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

  <span class="token function">transform</span><span class="token punctuation">(</span>html<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>sanitizer<span class="token punctuation">.</span><span class="token function">bypassSecurityTrustHtml</span><span class="token punctuation">(</span>html<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We can then use the pipe this way:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>SafeHtmlPipe<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;div [innerHTML]="someHtmlContent | safeHtml">
  &lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">TestComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>And this will effectively inject the HTML into the DOM, by bypassing the typical Angular XSS defenses.</p>
<p>Remember, you are now responsible for the safety of the code that was just injected!</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to my newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>Signals</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h1 id="summary">Summary</h1>
<p>Angular has made sure to build an array of code injection defenses in its template rendering engine, which is awesome.</p>
<p>But sometimes, only in some very concrete practical scenarios, we really want the ability to inject some HTML directly into the DOM.</p>
<p>This usually has to do with the use of rich-text editors.</p>
<p>So for those rare cases only, we can leverage the DOM Sanitizer service.</p>
<p>The SafeHtml pipe that we provided makes it easy to conveniently inject code if you need to, but remember:</p>
<blockquote>
<p>You <em>need</em> to make sure as much as possible that the code is actually safe to inject, so be mindful of this and only use this functionality when and if you really need it!</p>
</blockquote>
<p>I hope this post helped, let me know in the comments below if you have any questions.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular 17.1 Is Out: What&#39;s New? (Top 8 New Features)</title>
      <link>https://blog.angular-university.io/angular-17-1-release/</link>
      <guid isPermaLink="false">65b793a3546bb800015177e5</guid>
      <pubDate>Mon, 29 Jan 2024 12:47:57 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>The Angular 17.1 release is out. Let&#39;s do a quick summary of all its major features, with an emphasis on int&#39;s major new feature: signal inputs.</description>
      <content:encoded><![CDATA[<p>The Angular road to full application-wide signal-based reactivity continues with the latest Angular 17.1 release.</p>
<p>We just made one major step forward with the inclusion of Signal Inputs in 17.1, and besides that, we have a few other interesting features that we are going to cover in this post.</p>
<p>So without further ado, let's get started!</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>Input Signals</li>
<li>New Router info parameter</li>
<li>New Test Runner</li>
<li>Improved control flow migration</li>
<li>Application builder migration</li>
<li>Development server shortcuts</li>
<li>Angular Material support for hydration</li>
<li>Typescript and Vite upgrades</li>
<li>Summary</li>
</ul>
<h2 id="input-signals">Input Signals</h2>
<p>By far the biggest feature that has been released in Angular 17.1 is signal inputs.</p>
<p>In this post, we are just going to give you the gist of signal inputs, but if you want a deep dive into Angular Signals, check out this other article I wrote: <a href="https://blog.angular-university.io/angular-signal-inputs/">Angular Signal Inputs</a>.</p>
<p>A signal input is a new signal-based alternative to the traditional <code>@Input</code> decorator.</p>
<p>Here is what a signal input looks like:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;h1>Counter value: {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  value <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Our input value is now a signal! So we finally have a reactive component input primitive in Angular.</p>
<p>Notice in the template that to access the actual value of the signal, we need to invoke the signal as a function using <code>()</code>.</p>
<p>To learn more about signal inputs, check this video on the Angular University YouTube Channel:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/WrYOsgOsN6M?si=3d0cjF9buxvrreoW" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<h2 id="new-router-info-parameter">New Router info parameter</h2>
<p>Next up, we have available a new advanced router option called the <code>info</code> parameter.</p>
<p>Here is how we can use it:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">(click)</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>onIncrement()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    Increment
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> 
    <span class="token attr-name">routerLink</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>home<span class="token punctuation">"</span></span> 
    <span class="token attr-name">[info]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>{hello: 'world'}<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    Navigate to Home
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>So now in a router navigation, you can add an extra transient <code>info</code> parameter object.</p>
<p>This object is going to be part of the NavigationExtras object.</p>
<p>You can retrieve it in the following way:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">HomeComponent</span> <span class="token punctuation">{</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token keyword">private</span> router<span class="token operator">:</span> Router<span class="token punctuation">)</span> <span class="token punctuation">{</span>

  <span class="token punctuation">}</span>

  <span class="token function">ngOnInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span>events
      <span class="token punctuation">.</span><span class="token function">pipe</span><span class="token punctuation">(</span>
        <span class="token function">filter</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">=></span> e <span class="token keyword">instanceof</span> <span class="token class-name">NavigationEnd</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        <span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">=></span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>router
                <span class="token punctuation">.</span><span class="token function">getCurrentNavigation</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                    <span class="token operator">?.</span>extras<span class="token punctuation">.</span>info<span class="token punctuation">)</span>
      <span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span><span class="token punctuation">(</span>info<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>info<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that you can pass the info parameter either programmatically or by using the declarative router link API.</p>
<p>By getting the current navigation and from the extras object, you can grab the <code>info</code> parameter.</p>
<p>Notice that this <code>info</code> parameter is not being persisted in the browser history API, so if you hit the back-and-forth button on the browser, it's not going to be reflected in the URL.</p>
<p>For example, if you click on the <code>Navigate to Home</code> button, you're going to notice that nothing shows up in the URL, so the <code>info</code> extra parameter is not persisted in the history stack.</p>
<p>If you hit back and forward again, the <code>info</code> parameter is not going to be passed.</p>
<p>The <code>info</code> extra parameter is purely transient information that you might want to use in certain situations.</p>
<p>Most of the time, this is not a feature that you would be using every single day, but if you ever need to pass some extra information in specific route navigation without that information getting persisted in the URL, now there is a way to do it using a standard Angular API.</p>
<h2 id="new-web-test-runner">New Web Test Runner</h2>
<p>Next up is the new <a href="https://modern-web.dev/docs/test-runner/overview/" target="_blank" rel="noopener">Web Test Runner</a> that you now have available.</p>
<p>This browser test runner is in principle going to be the future replacement of Karma, which is now over 10 years old.</p>
<p>If you want to already start using this Web Test Runner, you need to install the following package in your project:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash"><span class="token function">npm</span> <span class="token function">install</span> @web/testrunner --save-dev
</code></pre></div>
<p>The test runner itself is production-ready, but its integration with Angular is still experimental.</p>
<p>You can replace Karma with this test runner in the following way:</p>
<ul>
<li>Go to your <code>angular.json</code> file.</li>
<li>Go to your <code>builder</code> configuration for your test task.</li>
</ul>
<div class="code-block"><span class="code-lang">json</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-json"><code class="language-json"><span class="token property">"test"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
  <span class="token property">"builder"</span><span class="token operator">:</span> <span class="token string">"@angular-devkit/build-angular:karma"</span><span class="token punctuation">,</span>
  <span class="token property">"options"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token property">"main"</span><span class="token operator">:</span> <span class="token string">"src/test.ts"</span><span class="token punctuation">,</span>
    <span class="token property">"karmaConfig"</span><span class="token operator">:</span> <span class="token string">"./karma.conf.js"</span><span class="token punctuation">,</span>
    <span class="token property">"polyfills"</span><span class="token operator">:</span> <span class="token string">"src/polyfills.ts"</span><span class="token punctuation">,</span>
    <span class="token property">"tsConfig"</span><span class="token operator">:</span> <span class="token string">"src/tsconfig.spec.json"</span><span class="token punctuation">,</span>
    <span class="token property">"scripts"</span><span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token property">"styles"</span><span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token string">"src/styles.scss"</span>
    <span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token property">"assets"</span><span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token string">"src/assets"</span><span class="token punctuation">,</span>
      <span class="token string">"src/favicon.ico"</span>
    <span class="token punctuation">]</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span>
</code></pre></div>
<ul>
<li>Here, instead of <code>karma</code>. Simply use the <code>web-test-runner</code> in the following way: <code>web-test-runner</code>.</li>
</ul>
<div class="code-block"><span class="code-lang">json</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-json"><code class="language-json"><span class="token property">"test"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
  <span class="token property">"builder"</span><span class="token operator">:</span> <span class="token string">"@angular-devkit/build-angular:web-test-runner"</span><span class="token punctuation">,</span>
  <span class="token property">"options"</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token property">"main"</span><span class="token operator">:</span> <span class="token string">"src/test.ts"</span><span class="token punctuation">,</span>
    <span class="token property">"karmaConfig"</span><span class="token operator">:</span> <span class="token string">"./karma.conf.js"</span><span class="token punctuation">,</span>
    <span class="token property">"polyfills"</span><span class="token operator">:</span> <span class="token string">"src/polyfills.ts"</span><span class="token punctuation">,</span>
    <span class="token property">"tsConfig"</span><span class="token operator">:</span> <span class="token string">"src/tsconfig.spec.json"</span><span class="token punctuation">,</span>
    <span class="token property">"scripts"</span><span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token property">"styles"</span><span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token string">"src/styles.scss"</span>
    <span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token property">"assets"</span><span class="token operator">:</span> <span class="token punctuation">[</span>
      <span class="token string">"src/assets"</span><span class="token punctuation">,</span>
      <span class="token string">"src/favicon.ico"</span>
    <span class="token punctuation">]</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span>
</code></pre></div>
<p>Now, if you run your tests here in your command line using the usual command <code>ng test</code>, you are going to see that the new Web Test Runner is being used!</p>
<h2 id="improved-control-flow-migration">Improved control flow migration</h2>
<p>Next up, we have several improvements on the Angular CLI migrations.</p>
<p>The existing control flow migration is now updated and improved.</p>
<p>A lot of bugs were fixed, and new features were added, so if you want to migrate your projects from <code>*ngFor</code>, <code>*ngIf</code>, <code>*ngSwitch</code> to the new control flow syntax: <code>@if</code>, <code>@for</code>, <code>@switch</code>, you can run this migration:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng generate @angular/core:control-flow
</code></pre></div>
<p>Notice that the migration itself is still on developer preview, but this new version is much improved, so we might want to try it out.</p>
<h2 id="application-builder-migration">Application builder migration</h2>
<p>Still on the topic of Angular CLI migrations, if you want to upgrade your existing legacy project to use the new application Builder.</p>
<p>You have a new migration available, and your <code>angular.json</code> file is going to be updated to use the new application Builder:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng update @angular/cli <span class="token parameter variable">--name</span> <span class="token operator">=</span>use-application-builder
</code></pre></div>
<h2 id="new-angular-cli-development-server-shortcuts">New Angular CLI Development server shortcuts</h2>
<p>Next up, there are a couple of nice developer experience improvements in the Angular CLI development server.</p>
<p>Notice this new message on the Angular CLI developer server:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">Application bundle generation complete. [0.281 seconds]
Watch mode enabled. Watching for file changes...

Local: http://localhost:4200/
press  + enter to show help
</code></pre></div>
<p>If you press <code>H</code> plus <code>Enter</code>, you will have a couple of useful shortcuts that we didn't have available before.</p>
<ul>
<li>
<p><code>r + enter</code>: to force the reload of the browser,</p>
</li>
<li>
<p><code>u + enter</code>: to show the server URL that we are currently running,</p>
</li>
<li>
<p><code>o + enter</code>: to open a new window in the browser with the Angular CLI development server</p>
</li>
<li>
<p><code>c + enter</code>: to clear the console and</p>
</li>
<li>
<p><code>q + enter</code>: to quit.</p>
</li>
<li>
<p>So go ahead and try out the new shortcuts, it's a very nice improvement on the developer experience!</p>
</li>
</ul>
<h2 id="angular-material-support-for-ssr-client-hydration">Angular Material support for SSR client hydration</h2>
<p>Next up, we have some important improvements in the <a href="https://material.angular.io/" target="_blank" rel="noopener">Angular material Library</a>.</p>
<p>Now all the Angular material components are fully Standalone, and also they support server-side rendering client hydration.</p>
<p>This means that if you are building your application using Angular Material, your front end will no longer re-render everything that the server has just rendered if you are using client-side hydration, which is recommended.</p>
<p>Go ahead and check out a video that I have here on the channel: <a href="https://www.youtube.com/watch?v=U1MP4uCuUVI" target="_blank" rel="noopener">The Angular SSR Deep dive</a>, where I explain in detail client hydration and how server-side rendering works in general.</p>
<h2 id="typescript-and-vite-upgrades">Typescript and Vite upgrades</h2>
<p>We also have an upgrade to <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-3.html" target="_blank" rel="noopener">TypeScript 5.3</a> and to Vite 5 at the level of the Angular CLI build.</p>
<p>And that's it for the 17.1 release, not bad right?</p>
<p>If you want to get notified when new Angular releases are out and get a comprehensive summary like this one each time by email, I invite you to subscribe to my newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>Signals</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>We have seen in this post a quick summary of all the eight major new features of Angular 17.1 that are just out.</p>
<p>The major feature is signal inputs, which is a new signal-based alternative to the traditional <code>@Input</code> decorator.</p>
<p>This is a major step forward in the whole Angular signal-based reactivity story, and I anticipate that we are going to see more and more of these signal-based features in the near future!</p>
<p>Let me know if you have any questions or comments, I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Signal Inputs: Complete Guide to input()</title>
      <link>https://blog.angular-university.io/angular-signal-inputs/</link>
      <guid isPermaLink="false">65b2921e8c22930001b3661c</guid>
      <pubDate>Fri, 26 Jan 2024 12:04:52 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guided tour of Angular Signal Inputs, covering how they compare to the @Input decorator, and how they help make the OnChanges lifecycle hook less needed. </description>
      <content:encoded><![CDATA[<p>In this post, we are going to cover the latest step in the Angular journey to full application-wide reactivity: Angular Signal Inputs.</p>
<p>We are going to compare this feature originally introduced in Angular 17.1 to its traditional counterpart, the <code>@Input</code> decorator.</p>
<p>We're going to cover all the available options for input signals and we're going to learn how signal inputs can provide us with a better alternative to the traditional <code>OnChanges</code> lifecycle hook.</p>
<p>So without further ado, let's get started learning Angular signal inputs!</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<ul>
<li>Converting @Input to a Signal Input</li>
<li>So what is the advantage of using Signal Inputs?</li>
<li>What about the parent component?</li>
<li>Replacing <code>OnChanges</code> with a signal <code>effect()</code></li>
<li>Signal input options: required, alias and transform options</li>
<li>Setting alias properties for signal inputs</li>
<li>Defining input transforms for signal inputs</li>
<li>Summary</li>
</ul>
<p>If you would like to learn about signal inputs in video format, check out this video on the <a href="https://www.youtube.com/@AngularUniversity" target="_blank" rel="noopener">Angular University YouTube channel</a>:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/WrYOsgOsN6M?si=B75vP0yorRoaLZ3Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<h2 id="converting-input-to-a-signal-input">Converting @Input to a Signal Input</h2>
<p>The best way to understand signal inputs is to compare them to the traditional <code>@Input</code> decorator.</p>
<p>You are probably already familiar with the Angular <code>@Input()</code> decorator, which is one of the cornerstones of the framework.</p>
<p>If not, you can check out here a detailed explanation about it: <a href="https://blog.angular-university.io/angular-input/">Angular @Input: Complete Guide</a>.</p>
<p>Let's then take a simple component written using the <code>@Input</code> decorator and convert it to use signal inputs.</p>
<p>Let's start with a simple <code>CounterComponent</code> that we are using in our application:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CounterComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;counter [value]="counter" />
    &lt;button (click)="onIncrement()">
    Increment
&lt;/button></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
  counter <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
  <span class="token function">onIncrement</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token operator">++</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This is just a simple component that takes as an input a counter value and displays it on the screen.</p>
<p>Let's see the <code>CounterComponent</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;h1>Counter value: {{ value }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token keyword">implements</span> <span class="token class-name">OnChanges</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  value <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

  <span class="token function">ngOnChanges</span><span class="token punctuation">(</span>changes<span class="token operator">:</span> SimpleChanges<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> change <span class="token operator">=</span> changes<span class="token punctuation">[</span><span class="token string">"value"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>change<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>
      <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">New value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>change<span class="token punctuation">.</span>currentValue<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, this is just a simple component that prints out to the console the new values of a counter.</p>
<p>The <code>CounterComponent</code> is written with the traditional <code>@Input</code> decorator.</p>
<p>See that we have the <code>ngOnChanges</code> lifecycle hook on the component, that we are using to detect when a new value is available for the <code>@Input</code> <code>value</code> property.</p>
<p>If there is a change in one of the input properties, namely the counter value property, we then retrieve the current value of the counter and log it in our console.</p>
<p>This is all traditional Angular, nothing new here.</p>
<p>Now, we are going to reimplement this same example but <strong>this time around using input signals!</strong></p>
<p>Here is what our <code>CounterComponent</code> will look like after the refactoring:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;h1>Counter value: {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  value <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>And that's it! Our code now works in the same way.</p>
<p>Or almost...</p>
<p>Notice the use of <code>()</code> when accessing the value on the template:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Counter value: {{ value() }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>
`,
</code></pre></div>
<p>You might be wondering why the <code>()</code> is necessary, and why we are not just accessing the value directly like this:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Counter value: {{ value }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>
`,
</code></pre></div>
<p>The issue is, if we try to run this, it won't work!</p>
<p>We will get some weird error like a function printed out in place of the value:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">The counter value is function inputValueFn() { producerAccessed(node); if (node.value === REQUIRED_UNSET_VALUE) { throw new RuntimeError(-950, ngDevMode &amp;&amp; &quot;Input is required but no value is available yet.&quot;); } return node.value; }

</code></pre></div>
<p>And here is a partial stack trace:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">Error in src/main.ts (8:42)
value is a function and should be invoked: value()
</code></pre></div>
<p>So what is going on here?</p>
<p>You see, the value property is no longer a plain numeric value.</p>
<p>Instead, it's a <em>signal input property</em>, whose emitted values are numeric.</p>
<p>So value is no longer a <code>number</code>, it's a <code>Signal&lt;number&gt;</code>.</p>
<p>So just like with any signal, we need to invoke it using <code>()</code> to get the current value.</p>
<p>If you want to learn more about signals, check out this other guide: <a href="https://blog.angular-university.io/angular-signals/">Angular Signals: Complete Guide</a>.</p>
<h2 id="so-what-is-the-advantage-of-using-signal-inputs">So what is the advantage of using Signal Inputs?</h2>
<p>The main advantage is noticeable when you are writing your components in a reactive style, using signals.</p>
<p>Now all your component inputs are themselves signals, so it's very easy to derive computed signals from them, define effects that react to input changes, and so on.</p>
<p>So now with signal inputs it's much easier to write your components in a reactive, signal-based style.</p>
<h2 id="what-about-the-parent-component">What about the parent component?</h2>
<p>Notice that after this refactoring to use input signals, we did not have to change anything in the parent component for the <code>CounterComponent</code> to work.</p>
<p>In the parent component we still have:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-root"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;counter [value]="counter" />
    &lt;button (click)="onIncrement()">
    Increment
    &lt;/button></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
    counter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token operator">...</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We are still passing the counter value to the <code>CounterComponent</code> via the <code>value</code> property, as usual, just like in the case when we were using the @Input decorator.</p>
<h2 id="replacing-onchanges-with-a-signal-effect">Replacing <code>OnChanges</code> with a signal <code>effect()</code></h2>
<p>So what are some of the other benefits of signal inputs?</p>
<p>Remember, in our old code using the @Input decorator, we were able to get the changes in the <code>@Input</code> decorator using the <code>ngOnChanges</code> lifecycle hook.</p>
<p>We can still do that with signal inputs, but this time around using the <code>effect</code> API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;h1>Counter value: {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  value <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">New value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that the effect API is not specific to signal inputs, this is a general-purpose API that can be used with any signal.</p>
<p>You can read more about it on this <a href="https://blog.angular-university.io/angular-signals/">signals guide</a>.</p>
<p>Let's break down what we did above with the use of the <code>effect</code> API:</p>
<ul>
<li>We created a constructor and created an effect</li>
<li>Inside the callback function in the <code>effect</code> API, we logged the current value of the signal input (which is the new counter value) to the console.</li>
<li>We accessed the new counter value from the signal input <code>value</code> using the <code>this</code> keyword.</li>
<li>Accessing the signal input <code>value</code> using the <code>this</code> keyword inside the effect API tells it that the signal input <code>value</code> is a dependency, so the <code>effect</code> will re-run whenever the signal input changes.</li>
</ul>
<p>If you try this out, you will see that this new version is working perfectly, just like the initial version based on <code>OnChanges</code>.</p>
<p>You can also see that the new code with the signal input and effect is significantly easier to read.</p>
<p>So this is one of the several advantages of input signals: we no longer need to use OnChanges for most us cases.</p>
<p>Let's now look at some other options that we have available for signal inputs.</p>
<h2 id="signal-input-options-required-alias-and-transform-options">Signal input options: required, alias and transform options</h2>
<p>Signal inputs have just the same usual options and defaults as a normal @Input.</p>
<p>For example, just like with @Input, a signal input is optional by default.</p>
<p>But if we instead want to make it required, we can do so like this:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;h1>The counter value is {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>

  value <span class="token operator">=</span> input<span class="token punctuation">.</span><span class="token generic-function"><span class="token function">required</span><span class="token generic class-name"><span class="token operator">&lt;</span><span class="token builtin">number</span><span class="token operator">></span></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token operator">...</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Now this becomes a required input!</p>
<p>Notice that even though this property is required, we <em>don't</em> need to pass an initial value.</p>
<p>This is because the initial value should be passed by the parent component via the template.</p>
<p>If we try to run this component <em>without</em> an input value, we're going to get an error.</p>
<div class="code-block"><span class="code-lang">sh</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash"><span class="token punctuation">[</span>ERROR<span class="token punctuation">]</span> NG8008: Required input <span class="token string">'value'</span> from component 
CounterComponent must be specified. <span class="token punctuation">[</span>plugin angular-compiler<span class="token punctuation">]</span>
</code></pre></div>
<h2 id="setting-alias-properties-for-signal-inputs">Setting alias properties for signal inputs</h2>
<p>Just like with @Input, we can define an alias name for our input property:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;h1>The counter value is {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>

  value <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
    alias<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token operator">...</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We can then pass the value to the <code>CounterComponent</code> via the <code>counter</code> property, instead of <code>value</code>:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>counter</span> <span class="token attr-name">[counter]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>counter<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<h2 id="defining-input-transforms-for-signal-inputs">Defining input transforms for signal inputs</h2>
<p>It's also possible to define a transform function for the signal input property.</p>
<p>The transform option allows us to transform the value of the property value before it gets emitted by the signal input.</p>
<p>Let's say that we want to transform the value passed in via the signal input property and multiply it by 100:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;h1>counter value: {{ value() }}&lt;/h1></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  value <span class="token operator">=</span> <span class="token function">input</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
    alias<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
    <span class="token function-variable function">transform</span><span class="token operator">:</span> <span class="token punctuation">(</span>value<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">)</span> <span class="token operator">=></span> value <span class="token operator">*</span> <span class="token number">100</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>If we click on the increment button in the parent component, the transformation will be applied as expected:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">1000

1100

1200
</code></pre></div>
<p>And with this, we have covered all the available options for signal inputs!</p>
<p>As you can see, signal inputs work just like a standard @Input, except that they are reactive and signal-based.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to my newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>Signals</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>As you can see, input signals are a great step forward on the road to full application-wide Angular reactivity.</p>
<p>In a nutshell, input signals behave just like a plain regular @Input, except that they are signal-based.</p>
<p>They have all the same usual options as @Input, such as <code>required</code>, <code>alias</code>, and<br>
<code>transform</code>.</p>
<p>We also saw how we can use the <code>effect</code> API to replace the <code>ngOnChanges</code> lifecycle hook if we are writing our components using signals.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Loading Indicator: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-loading-indicator/</link>
      <guid isPermaLink="false">65a7dff9d5cd730001d938cb</guid>
      <pubDate>Wed, 17 Jan 2024 17:49:51 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete hands-on guide on how to build a loading indicator in Angular. The spinner will accept a customizable UI via content projection, and it will be integrated with the router. We will use an HTTP interceptor to turn it on for backend requests.</description>
      <content:encoded><![CDATA[<p>This post is a complete guide on how to create a loading indicator widget in Angular.</p>
<p>We will explain step by step the design of this widget. We will create a global loading indicator component and the corresponding loading indicator service to go with it.</p>
<p>We will learn how to make the loading indicator component detect route transitions and display the indicator while the route is changing.</p>
<p>We will also learn how we can easily turn on or off the loading indicator for every HTTP request.</p>
<p>Also, we will see how to use the loading when loading data from a backend using Observables and async-await.</p>
<p>Besides being useful on its own, building this widget makes up for a nice Angular exercise, were we will explore several features and patterns of the framework.</p>
<p>So without further ado, let's get started! 🚀</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>Design goals for the loading indicator</li>
<li>Building the loading indicator service</li>
<li>Building the loading indicator component</li>
<li>Using the loading indicator globally</li>
<li>Automatically showing the loading indicator when loading data from the backend</li>
<li>Don't turn on the loading indicator for certain HTTP requests</li>
<li>Integrating the loading indicator with the router</li>
<li>Proving an alternative UI for the loading indicator</li>
<li>Summary</li>
</ul>
<h2 id="design-goals-for-the-loading-indicator">Design goals for the loading indicator</h2>
<p>First, let's define some core features that we want to have in our loading indicator:</p>
<ul>
<li>we should be able to turn it on and off from <em>anywhere</em> in the application. We shouldn't need to have direct access to the indicator component to do that.</li>
<li>we should be able to integrate the loading indicator with the router so that it displays on route transitions.</li>
<li>we should be able to automatically show the loading indicator when loading data from the backend.</li>
<li>For certain HTTP requests, we should be able to not turn on the loading indicator, for example if we want to silently trigger the request in the background without the user noticing it</li>
<li>the loading indicator should have a default UI design based on Angular Material, but we should be able to customize it if we want to</li>
</ul>
<p>The loading indicator should have:</p>
<ul>
<li>a loading component, that's the spinner element itself</li>
<li>a loading service, that can be usee to control the indicator from anywhere on the application</li>
</ul>
<p>With these design goals in mind, let's start building our loading indicator widget!</p>
<h2 id="building-the-loading-indicator-service">Building the loading indicator service</h2>
<p>Let's start building the service that we are going to use to activate/deactivate the loading indicator.</p>
<p>The main goal of this service is to allow control of the behavior of the loading indicator even from a component that has no direct access to the loading component.</p>
<p>Imagine for example a global loading indicator, that's displayed right in the center of the screen.</p>
<p>We want to be able to turn on and off this loading indicator from <em>anywhere</em> in the application.</p>
<p>In order to achieve this, instead of using the loading component directly to turn on/off the indicator, we are going to do that indirectly via a shared service.</p>
<p>We will be able to inject this service anywhere that we want, and control the loading indicator via the service.</p>
<p>We are going to write this service in a reactive style using RxJs.</p>
<p>Here is the full code of the service:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Injectable</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  providedIn<span class="token operator">:</span> <span class="token string">"root"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">LoadingService</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> loadingSubject <span class="token operator">=</span> 
    <span class="token keyword">new</span> <span class="token class-name">BehaviorSubject<span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  loading$ <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>loadingSubject<span class="token punctuation">.</span><span class="token function">asObservable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">loadingOn</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>loadingSubject<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">loadingOff</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>loadingSubject<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Let's break this code down, step by step:</p>
<ul>
<li>we are using the <a href="https://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/">Observable Data Service</a> pattern in this service.</li>
<li>we are using a BehaviorSubject to store the current state of the loading indicator.</li>
<li>we are keeping the subject private, to keep control over who can emit values using it.</li>
<li>we are exposing the subject as an observable so that any component can subscribe to it and get notified when the loading indicator is turned on or off.</li>
<li>we are exposing two simple public methods to turn the loading indicator on or off.</li>
</ul>
<p>As you can see, this service is super easy to use!</p>
<p>This service is declared globally as a singleton, so you can inject it anywhere on the application and use it to control the global loading indicator.</p>
<p>You can do so even in components deeply nested in the component tree, that don't have access to the global loading indicator.</p>
<h2 id="building-the-loading-indicator-component">Building the loading indicator component</h2>
<p>Now let's build the component itself.</p>
<p>For the default UI of the indicator, we are going to use an Angular Material spinner component, but remember that we are going to be able to replace this with something else if we want to.</p>
<p>Let's show here the full code of the component, and then we are going to break it down step by step.</p>
<p>Let's start with the styling of the component:</p>
<div class="code-block"><span class="code-lang">css</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-css"><code class="language-css"><span class="token selector">.spinner-container</span> <span class="token punctuation">{</span>
  <span class="token property">position</span><span class="token punctuation">:</span> fixed<span class="token punctuation">;</span>
  <span class="token property">height</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
  <span class="token property">width</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
  <span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span>
  <span class="token property">justify-content</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
  <span class="token property">align-items</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
  <span class="token property">top</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
  <span class="token property">left</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
  <span class="token property">background</span><span class="token punctuation">:</span> <span class="token function">rgba</span><span class="token punctuation">(</span>0<span class="token punctuation">,</span> 0<span class="token punctuation">,</span> 0<span class="token punctuation">,</span> 0.32<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token property">z-index</span><span class="token punctuation">:</span> 2000<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This <code>spinner-container</code> CSS class is going to be used to style the background that will cover the page while the loading is ongoing.</p>
<p>Let's now have a look at the template of the loading component:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@if(loading$ | async) {

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>spinner-container<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  @if(customLoadingIndicator) {

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ng-container</span> 
    <span class="token attr-name">*ngTemplateOutlet</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>customLoadingIndicator<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>

  } @else {

  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mat-spinner</span> <span class="token punctuation">/></span></span>

  }
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

}
</code></pre></div>
<p>Notice that we are using the @if template syntax. To read more about it, you can check out this guide: <a href="https://blog.angular-university.io/angular-if/">Angular @if - The Complete Guide</a>.</p>
<p>Let's break down the template code step by step:</p>
<ul>
<li>the loading indicator is only going to be displayed if the <code>loading$</code> observable emits the value true, and hidden otherwise</li>
<li>the default UI for the loading indicator is the <code>&lt;mat-spinner /&gt;</code> component from Angular Material</li>
<li>But there is also the possibility of providing a custom UI for the component, by providing a template called <code>customLoadingIndicator</code> to the component via content projection</li>
</ul>
<p>We will dive deeper into the custom UI feature and the use of <code>ngTemplateOutlet</code> later on.</p>
<p>Right now, let's have a look at the component class of the loading indicator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"loading-indicator"</span><span class="token punctuation">,</span>
  templateUrl<span class="token operator">:</span> <span class="token string">"./loading-indicator.component.html"</span><span class="token punctuation">,</span>
  styleUrls<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">"./loading-indicator.component.scss"</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>MatProgressSpinnerModule<span class="token punctuation">,</span> AsyncPipe<span class="token punctuation">,</span> NgIf<span class="token punctuation">,</span> NgTemplateOutlet<span class="token punctuation">]</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">LoadingIndicatorComponent</span> <span class="token keyword">implements</span> <span class="token class-name">OnInit</span> <span class="token punctuation">{</span>

  loading$<span class="token operator">:</span> Observable<span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">></span><span class="token punctuation">;</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  detectRouteTransitions <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">ContentChild</span></span><span class="token punctuation">(</span><span class="token string">"loading"</span><span class="token punctuation">)</span>
  customLoadingIndicator<span class="token operator">:</span> TemplateRef<span class="token operator">&lt;</span><span class="token builtin">any</span><span class="token operator">></span> <span class="token operator">|</span> <span class="token keyword">null</span> <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span>
  <span class="token keyword">private</span> loadingService<span class="token operator">:</span> LoadingService<span class="token punctuation">,</span> 
  <span class="token keyword">private</span> router<span class="token operator">:</span> Router<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>loading$ <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span>loading$<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">ngOnInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>detectRouteTransitions<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>router<span class="token punctuation">.</span>events
        <span class="token punctuation">.</span><span class="token function">pipe</span><span class="token punctuation">(</span>
          <span class="token function">tap</span><span class="token punctuation">(</span><span class="token punctuation">(</span>event<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>event <span class="token keyword">instanceof</span> <span class="token class-name">RouteConfigLoadStart</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
              <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>event <span class="token keyword">instanceof</span> <span class="token class-name">RouteConfigLoadEnd</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
              <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
          <span class="token punctuation">}</span><span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This is where it all comes together!</p>
<p>Let's discuss in the following sections the code of this component, and learn how each of these feature works, one at a time.</p>
<h2 id="using-the-loading-indicator-globally">Using the loading indicator globally</h2>
<p>Thanks to the loading service, we can use the loading indicator from anywhere in the application.</p>
<p>The first this that we need to do, is to set up the loading indicator component in the root component of the application.</p>
<p>Imagine that this is your root component app.component.html:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">routerLink</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/contact<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Contact<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">routerLink</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/help<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Help<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">routerLink</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>/about<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>About<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>router-outlet</span> <span class="token punctuation">/></span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-indicator</span> <span class="token punctuation">/></span></span>
</code></pre></div>
<p>The loading widget is in place, and it's turned off by default.</p>
<p>Now imagine that we would like to turn the loading indicator on and off from a child component, that doesn't have direct access to the loading component.</p>
<h2 id="how-to-use-the-loading-indicator-with-async-await-code">How to use the loading indicator with async/await code</h2>
<p>All we have to do is to inject the loading service in the component, and call the <code>loadingOn</code> and <code>loadingOff</code> methods:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"child-component"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CommonModule<span class="token punctuation">]</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;button (click)="onLoadCourses()">
  Load Courses
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponentComponent</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token keyword">private</span> loadingService<span class="token operator">:</span> LoadingService<span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>

  <span class="token function">onLoadCourses</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

      <span class="token comment">// load courses from backend</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>error<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// handle error message</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>We can see on the onLoadCourses method a common pattern of how to handle loading indicators while doing backend requests.</p>
<p>We start by turning the loading indicator on, then we do the backend request, and turn we turn the loading indicator off.</p>
<p>Notice that we turn the loading indicator off in the <code>finally</code> block so that it's always turned off, even if there is an error.</p>
<p>It would be a mistake to try to turn the loading indicator inside the try block, right before the catch block.</p>
<p>This is because if there is an error before that, the loading will not be turned off.</p>
<p>Instead, it will stay on forever and block the whole UI.</p>
<p>But notice that writing this type of code everywhere could be repetitive and error-prone, especially if you plan on applying the same logic to almost every single HTTP request in your application.</p>
<h2 id="automatically-showing-the-loading-indicator-when-loading-data-from-the-backend">Automatically showing the loading indicator when loading data from the backend</h2>
<p>To avoid writing this repetitive code everywhere, we can use an Http Interceptor to automatically turn the loading indicator on and off for every HTTP request.</p>
<p>Here is how we can do that:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">export</span> <span class="token keyword">const</span> SkipLoading <span class="token operator">=</span> 
  <span class="token keyword">new</span> <span class="token class-name">HttpContextToken<span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Injectable</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">LoadingInterceptor</span> 
    <span class="token keyword">implements</span> <span class="token class-name">HttpInterceptor</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token keyword">private</span> loadingService<span class="token operator">:</span> LoadingService<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token punctuation">}</span>

  <span class="token function">intercept</span><span class="token punctuation">(</span>
    req<span class="token operator">:</span> HttpRequest<span class="token operator">&lt;</span><span class="token builtin">any</span><span class="token operator">></span><span class="token punctuation">,</span>
    next<span class="token operator">:</span> HttpHandler
  <span class="token punctuation">)</span><span class="token operator">:</span> Observable<span class="token operator">&lt;</span>HttpEvent<span class="token operator">&lt;</span><span class="token builtin">any</span><span class="token operator">>></span> <span class="token punctuation">{</span>
    <span class="token comment">// Check for a custom attribute </span>
    <span class="token comment">// to avoid showing loading spinner</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>req<span class="token punctuation">.</span>context<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>SkipLoading<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// Pass the request directly to the next handler</span>
      <span class="token keyword">return</span> next<span class="token punctuation">.</span><span class="token function">handle</span><span class="token punctuation">(</span>req<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">// Turn on the loading spinner</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> next<span class="token punctuation">.</span><span class="token function">handle</span><span class="token punctuation">(</span>req<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">pipe</span><span class="token punctuation">(</span>
      <span class="token function">finalize</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token comment">// Turn off the loading spinner</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>loadingService<span class="token punctuation">.</span><span class="token function">loadingOff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Before breaking this code down, let's see how we can register this interceptor in the application:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token function">bootstrapApplication</span><span class="token punctuation">(</span>AppComponent<span class="token punctuation">,</span> <span class="token punctuation">{</span>
  providers<span class="token operator">:</span> <span class="token punctuation">[</span>
    <span class="token function">importProvidersFrom</span><span class="token punctuation">(</span>
      BrowserModule<span class="token punctuation">,</span>
      AppRoutingModule<span class="token punctuation">,</span>
      RouterModule<span class="token punctuation">,</span>
      LoadingService
    <span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span>
      provide<span class="token operator">:</span> <span class="token constant">HTTP_INTERCEPTORS</span><span class="token punctuation">,</span>
      useClass<span class="token operator">:</span> LoadingInterceptor<span class="token punctuation">,</span>
      multi<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>As you can see, we need to use a multi-provider, meaning that this injectable token will return an array of interceptors,<br>
as opposed to only one.</p>
<p>And now, let's break down the interceptor code.</p>
<p>As you can see, the interceptor is simply creating a clone of the original request.</p>
<p>Then it turns on the loading indicator, and it turns it off using the finalize operator, meaning that the indicator is only turned off when the request Observable is either completed or it errors out.</p>
<p>Because we know that an HTTP Observable will always emit a value and then complete (or error out), we know that the finalize operator will always be called and the loading indicator will be hidden.</p>
<h2 id="don-t-turn-on-the-loading-indicator-for-certain-http-requests">Don't turn on the loading indicator for certain HTTP requests</h2>
<p>But notice that in the code of the interceptor we are also checking for a <code>HttpContextToken</code> called <code>SkipLoading</code>.</p>
<p>If the value of this context is <code>true</code>, we are <em>not</em> turning on the loading indicator.</p>
<p>This could be useful in certain scenarios.</p>
<p>Imagine a scenario where we are periodically polling the server in the background every 10 seconds, to refresh the data of a chart.</p>
<p>In that case, we <em>don't</em> want to show the loading indicator every time, so we can skip it by setting the <code>SkipLoading</code> Http context to true.</p>
<p>Here is how we can disable the loading indicator for a single HTTP request:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">this</span><span class="token punctuation">.</span>http<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"/api/courses"</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  context<span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">HttpContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>SkipLoading<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<h2 id="integrating-the-loading-indicator-with-the-router">Integrating the loading indicator with the router</h2>
<p>Another common feature that we usually want to put in place, is to show the loading indicator during route transitions.</p>
<p>That is where the <code>detectRouteTransitions</code> input property comes into play.</p>
<p>If we set this property to true, the loading indicator will automatically turn on and off when the route is changing.</p>
<p>Here is how we can use this feature in our application root component:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-indicator</span> 
    <span class="token attr-name">[detectRouteTransitions]</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
</code></pre></div>
<h2 id="proving-an-alternative-ui-for-the-loading-indicator">Proving an alternative UI for the loading indicator</h2>
<p>The loading component also supports the possibility of providing an alternative UI for the loading indicator.</p>
<p>If you don't want to use the Angular Material spinner, you can instead provide a custom template to the component via content projection, like so:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-indicator</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ng-template</span> <span class="token attr-name">#loading</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>custom-spinner<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>custom-spinner.gif<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ng-template</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>loading-indicator</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>In this case, the custom template will be displayed instead of the Angular Material spinner.</p>
<p>Notice that for this to work, the custom template <em>needs</em> to be named &quot;loading&quot;, otherwise this will not work.</p>
<p>So how does the loading indicator component know that it should display the custom template instead of the default UI?</p>
<p>The loading indicator component first checks if the user provided a custom template via the <code>@ContentChild</code> decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">ContentChild</span></span><span class="token punctuation">(</span><span class="token string">"loading"</span><span class="token punctuation">)</span>
customLoadingIndicator<span class="token operator">:</span> TemplateRef<span class="token operator">&lt;</span><span class="token builtin">any</span><span class="token operator">></span> <span class="token operator">|</span> <span class="token keyword">null</span> <span class="token operator">=</span> <span class="token keyword">null</span>
</code></pre></div>
<p>If the user provided a custom template with the name &quot;loading&quot;, then that template is displayed, otherwise, the default UI is displayed:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@if(customLoadingIndicator) {

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ng-container</span> <span class="token attr-name">*ngTemplateOutlet</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>customLoadingIndicator<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>

} @else {

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mat-spinner</span> <span class="token punctuation">/></span></span>

}
</code></pre></div>
<p>The way that the custom template is applied to the loading component is via the <code>ngTemplateOutlet</code> directive.</p>
<p>You can read more about that directive here in this guide: <a href="https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/">Angular ng-template, ng-container, and ngTemplateOutlet - The Complete Guide To Angular Templates</a>.</p>
<p>And with this, we have covered all the features of our global loading indicator.</p>
<p>I think that this widget has all the features that you need for most applications.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>@Output</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this post, we have seen how to build a loading indicator widget using Angular.</p>
<p>The loading indicator has the following features:</p>
<ul>
<li>we can turn it on and off from anywhere in the application, thanks to the loading service</li>
<li>we can automatically turn it on and off for every HTTP request, thanks to an Http Interceptor</li>
<li>we can automatically turn it on and off during route transitions</li>
<li>we can provide a custom UI for the loading indicator if we need to, via content projection</li>
</ul>
<p>I hope you will enjoy using this widget, let me know if you have applied it in one of your projects and if you have further improvement suggestions.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @Output: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-output/</link>
      <guid isPermaLink="false">65a7adadd5cd730001d9385e</guid>
      <pubDate>Wed, 17 Jan 2024 13:35:23 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to the Angular @Output decorator and EventEmitter. Learn how to use @Output to emit custom component events, and avoid a common misunderstanding regarding its use.</description>
      <content:encoded><![CDATA[<p>Custom component events are a crucial feature of any web framework.</p>
<p>And in Angular, we can create component events by using the <code>@Output</code> decorator alongside <code>EventEmitter</code>.</p>
<p>In this guide, we will learn how to use <code>@Output</code> to emit custom component events, and talk about a <strong>common confusion that you might step into</strong> while designing component events.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post covers the following topics:</p>
<ul>
<li>What is <code>@Output</code>?</li>
<li>Basic Syntax of <code>@Output</code></li>
<li>What data type can @Output emit?</li>
<li>Parent-Child data communication using <code>@Output</code></li>
<li>Accessing emitted data in the template</li>
<li>Is it a must to pass the $event to the handler method?</li>
<li>Must the name be <code>$event</code> in the template?</li>
<li><code>@Output</code> with aliases</li>
<li>How to set outputs in the <code>@Component</code> decorator</li>
<li>How to set output alias in the <code>@Component</code> decorator</li>
<li>What type of data type can you bind to @Output?</li>
<li>Can the @Output be used to broadcast events to multiple components?</li>
<li>How often can I use @Output?</li>
<li>How can I specify the type of data emitted by an @Output?</li>
<li>Must @Output be used with EventEmitter?</li>
<li>Do the @Ouput and @Input have to be in the same component?</li>
<li>Do the custom events bubble up to the DOM?</li>
<li>What happens to the outputs when a component is extended?</li>
<li>Are output names case-sensitive?</li>
<li>Common mistakes when using <code>@Output</code></li>
<li>Summary</li>
</ul>
<h2 id="what-is-output">What is <code>@Output</code>?</h2>
<p><code>@Output</code> is a decorator that marks a component property as an output of the component.</p>
<p>It is a mechanism that allows an Angular component to report output events to its parent components.</p>
<p>The <code>@Output()</code> must be associated with an EventEmitter.</p>
<p>When an EventEmitter emits an event, any parent component listening to that event through an event binding can respond to it accordingly.</p>
<h2 id="basic-syntax-of-output">Basic Syntax of <code>@Output</code></h2>
<p>The basic syntax of <code>@Output</code> is as follows:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Output</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    alias<span class="token operator">?</span><span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span> propertyName <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span>type<span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p><code>alias</code>: The name of the DOM property to which the output property is bound.</p>
<p><code>propertyName</code>: The name of the property that emits events. This is a class field that is decorated with <code>@Output</code>. If we don't specify this, this will be the property name itself.</p>
<p><code>type</code>: This generic parameter defines the data type of the event payload. The consumers of the event will receive an instance of this type.</p>
<p>Here's an example of how <code>@Output()</code> is used:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;button (click)="emitEvent()">
  Send Data to Parent
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Output</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> 
  myEvent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">emitEvent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">"Hello World!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In the above example, the <code>ChildComponent</code> has a property <code>myEvent</code> which is decorated with <code>@Output</code>.</p>
<p>With this code, anytime that we want to report an event of type myEvent to the outside world, we can call the <code>emitEvent</code> method.</p>
<p>The parent component needs then to subscribe to the output event and react to it.</p>
<p>Here's how the parent component's template might look:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;app-child (myEvent)="handleEvent($event)" /></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  <span class="token function">handleEvent</span><span class="token punctuation">(</span>event<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>event<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The <code>ParentComponent</code> renders the <code>app-child</code>, and wants to get notified whenever the event myEvent occurs.</p>
<p>So it uses the <code>()</code> event syntax to bind to the <code>myEvent</code> event and assigns a handler method to it named <code>handleEvent</code>.</p>
<p>This <code>handleEvent</code> method gets called whenever the <code>myEvent.emit()</code> is called inside the child component.</p>
<p>The <code>handleEvent</code> method then receives the data emitted by the <code>myEvent</code> event.</p>
<p>Notice the use of the <code>$event</code> special variable. This variable contains the data passed to the emit() call.</p>
<p>So in this way, the child component has communicated with the parent component in a decoupled, event-driven way.</p>
<h2 id="output-with-aliases"><code>@Output</code> with aliases</h2>
<p>By default, the name of the <code>@Output()</code> property becomes also the name of the custom event. But for some reason, you might want to use a different name.</p>
<p>You can do so by supplying an alias to the <code>@Output</code> decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Output</span></span><span class="token punctuation">(</span><span class="token string">'customEvent'</span><span class="token punctuation">)</span> 
myEvent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The <code>customEvent</code> name will now be used to bind to the event of the child component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;app-child (customEvent)="handleEvent($event)" /></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  <span class="token function">handleEvent</span><span class="token punctuation">(</span>event<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>event<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>If we try to use the previous <code>(myEvent)</code> event-binding syntax, it will throw an error.</p>
<h2 id="avoid-a-common-mistake-when-using-output">Avoid a common mistake when using <code>@Output</code></h2>
<p>This mistake happens very frequently, and it can lead to code that is hard to maintain.</p>
<p>The <code>@Output</code> mechanism is meant to report custom events, but it's <em>not</em> meant to be used to explicitly trigger actions in other components.</p>
<p>The difference is perhaps subtle the first time you hear it, but it's crucial to understand it.</p>
<p>You see, these are two very different concepts, that we cannot mix together:</p>
<ul>
<li><strong>Event</strong>: it reports an internal change of state of the component</li>
<li><strong>Command</strong>: it tells another component explicitly to do a very specific action</li>
</ul>
<p>The difference is subtle but crucial.</p>
<p>When we send a command, we have a lot of information about the receiver of the command and what it's going to do in reponse to the command.</p>
<p>But that is not the case when talking about events.</p>
<p>Let's see an example of how this could occur and why that would be problematic:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;button (click)="onClick()">
  Trigger logic
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Output</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  updateTotalCoursesCounter <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">onClick</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>someBusinessLogic<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>updateTotalCoursesCounter<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice the name of this output: it's not an event, but a command.</p>
<p>This output tells some other external component outside of this child component to perform an explicit action.</p>
<p>The problem with this design is that this child component has way too much information about the internal workings of another completely unrelated component.</p>
<p>The placement of the business logic is likely at the wrong place in the application. It probably shouldn't be inside the child component.</p>
<p>Let's switch this to an event output instead:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;button (click)="onClick()">
  Trigger logic
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Output</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  somethingHappened <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">onClick</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>somethingHappened<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that here, we are just reporting to the outside of the component that something happened, but we are not telling the outside world what to do.</p>
<p>We are just reporting an internal change of state of the component, and it's for the outside world to decide what to do in response to that, if anything at all.</p>
<p>This way, the child component is not aware of what other components in the application are interested in this event, and the child component does not know what the other components will do with that information.</p>
<p>The child component makes no assumptions about how, where, when or if this custom event will be used.</p>
<p>It is up to the consumers of this output to decide what to do in response to the event:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;app-child (somethingHappened)="handleEvent()" /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  <span class="token function">handleEvent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>someBusinessLogic<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// update the total courses counter</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here the parent component detected the event and did something in response to it. The child component does not which parent component captured the event, or what it did in response to it.</p>
<p>Notice the placement of the business logic: it's now in the right place.</p>
<p>It would have been surprising to find this business logic inside the child component, as that's not where it belongs.</p>
<h2 id="the-main-takeaway-on-how-to-avoid-the-event-vs-command-design-pitfall">The main takeaway on how to avoid the Event vs Command design pitfall</h2>
<p>When designing your component outputs, remember the rule that an event is not a command, and that @Output is meant to report events, not to trigger actions explicitly in other components.</p>
<p>One good way of making sure that you are following this rule is to carefully inspect the name of the output.</p>
<p>If it's not a verb in past tense, check to see if the output is not being misused to trigger an action that the component should not know about.</p>
<p>A verb in the past tense is a good indicator that the output is just reporting an internal change in the component state, and not telling the outside world what to do.</p>
<p>Let's now cover some common FAQs related to the use of <code>Output</code>.</p>
<h2 id="faqs-about-output-and-eventemitter">FAQs about @Output and EventEmitter</h2>
<p>Here are some of the most frequently asked questions about <code>@Output</code> and<br>
<code>EventEmitter</code>.</p>
<h2 id="what-data-type-can-output-emit">What data type can @Output emit?</h2>
<p>The <code>@Output</code> EventEmitter can emit absolutely any data type.</p>
<p>It can emit primitive data types, objects or arrays:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token comment">// primitive values.</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">"Hello World!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token number">90</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// You can emit custom event objects</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token operator">:</span> <span class="token string">"Chidume Nnamdi"</span><span class="token punctuation">,</span>
  age<span class="token operator">:</span> <span class="token number">90</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token string">"4"</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> person <span class="token operator">=</span> <span class="token function">Person</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span>person<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<h2 id="is-it-a-must-to-pass-the-event-to-the-handler-method">Is it a must to pass the $event to the handler method?</h2>
<p>No, it isn't. You can still omit it even if the data type is not <code>void</code>.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> 
  &lt;app-child (myEvent)="handleEvent()" /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  <span class="token function">handleEvent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Hello World!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<h2 id="can-the-output-be-used-to-broadcast-events-to-multiple-components">Can the @Output be used to broadcast events to multiple components?</h2>
<p><code>@Output()</code> is intended for direct communication between the child component and the parent component. It's not possible or intended to use <code>@Output()</code> to broadcast events to multiple components.</p>
<h2 id="must-output-be-used-with-eventemitter">Must @Output be used with EventEmitter?</h2>
<p>The <code>@Output</code> must always be an instance of <code>EventEmitter</code>.</p>
<h2 id="do-the-custom-events-bubble-up-to-the-dom">Do the custom events bubble up to the DOM?</h2>
<p>No, the custom events do not bubble up to the DOM, unlike most standard browser events.</p>
<h2 id="is-manually-bubbling-custom-events-up-the-component-tree-a-good-idea">Is manually bubbling custom events up the component tree a good idea?</h2>
<p>No, this is an anti-pattern. Use instead a shared service to communicate between components that don't have a direct parent-child relationship.</p>
<h2 id="what-happens-to-the-outputs-when-a-component-is-extended">What happens to the outputs when a component is extended?</h2>
<p>When a component is extended, the child component inherits the outputs of the parent component.</p>
<h2 id="are-output-names-case-sensitive">Are output names case-sensitive?</h2>
<p>Yes, output names are case-sensitive. The name of the output property must match the name of the class field. Any mismatch at all will result in an error.</p>
<h2 id="how-to-set-outputs-in-the-component-decorator">How to set outputs in the <code>@Component</code> decorator</h2>
<p>Without using the <code>@Output</code> decorator, we can still set output properties for a component.</p>
<p>This is an alternative syntax that might come in handy in certain cases:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;button (click)="emitEvent()">
  Send Data to Parent
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  outputs<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">"myEvent"</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>

  myEvent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">emitEvent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">"Hello World!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<h2 id="how-to-set-output-alias-in-the-component-decorator">How to set output alias in the <code>@Component</code> decorator</h2>
<p>We do this by separating the names with a colon <code>:</code>. The name on the left-hand side is the name of the class field, while the name on the right-hand side is the alias name:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;button (click)="emitEvent()">
  Send Data to Parent
  &lt;/button> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  outputs<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token string">"myEvent: customEvent"</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  myEvent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EventEmitter<span class="token operator">&lt;</span><span class="token builtin">string</span><span class="token operator">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">emitEvent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>myEvent<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">"Hello World!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>@Output</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we went deep into the depths of the <code>@Output</code> decorator.</p>
<p>Besides the basic syntax and the features that it provides, we have learned that <code>@Output</code> is not meant to be explicitly used to trigger actions in other components but to report custom events that represent internal changes in the state of the component.</p>
<p>A good rule of thumb to follow is to check the output name and make sure that it's a verb in the past tense.</p>
<p>If that is the case, that is a good indication that the output mechanism is being used in a maintainable way.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @Input: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-input/</link>
      <guid isPermaLink="false">658328dad5cd730001d9375a</guid>
      <pubDate>Thu, 21 Dec 2023 12:56:49 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>Learn how to use the Angular @Input decorator with all its many extra options, including the super-useful input transforms mechanism.</description>
      <content:encoded><![CDATA[<p>I'm sure you already heard about the Angular <code>@Input</code> decorator!</p>
<p>This decorator allows us to pass data from a parent component to a child component, and it's one of the core building blocks of the framework.</p>
<p>What you might not know is that this decorator has a <strong>ton of extra features</strong> and options that were added over the years that you might not have heard about.</p>
<p>Specifically, we will focus a lot on the input transforms feature, which for most use cases can be used instead of input getters and setters or the @Attribute decorator.</p>
<p>Input transforms can also help us keep our templates more readable, by simplifying certain common use cases like boolean or numeric read-only properties.</p>
<p>So in this guide, I will explain the <code>@Input</code> decorator in detail with <em>all</em> its extra features, and provide examples for each scenario.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>The basics of how to use @Input</li>
<li>Required inputs</li>
<li>@Input with setters and getters</li>
<li>@Input with aliases</li>
<li>Input transforms</li>
<li>Built-in input transforms booleanAttribute and numberAttribute</li>
<li>@Input vs @Attribute: what are the differences?</li>
<li>When to use @Input vs @Attribute?</li>
<li>Summary</li>
</ul>
<h2 id="the-basics-of-how-to-use-input">The basics of how to use @Input</h2>
<p><code>@Input()</code> is an Angular decorator that marks a class property as an input property of the component.</p>
<p>The <code>@Input</code> decorator is used to pass data from a parent component to a child component.</p>
<p>Here is the basic usage of the <code>@Input</code> decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> name<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here the <code>@Input</code> decorator was used to mark the <code>name</code> property as an input property.</p>
<p>This means that a parent component using the ChildComponent can set the value of the <code>name</code> property using the property template binding syntax:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;child [name]="name" /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  name <span class="token operator">=</span> <span class="token string">"John Doe"</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>If the value of the <code>name</code> property changes in the parent component, then that change is going to get propagated via the <code>@Input()</code> decorator.</p>
<p>And that is the whole point of <code>@Input</code>!</p>
<p>Now, let's go beyon the basics. Let's start exploring what other extra features and configuration options we have available.</p>
<h2 id="required-inputs">Required inputs</h2>
<p>By default, inputs are optional, so there <em>won't</em> be a validation error when an input is not supplied.</p>
<p>Optionally we can mark an input as required like this:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    required<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  name<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In the above code, the <code>name</code> property is required, meaning that the parent component <em>must</em> supply a value for the <code>name</code> property.</p>
<p>If a value is not provided to the input property, then an error will be thrown:</p>
<div class="code-block"><span class="code-lang">sh</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash"><span class="token punctuation">[</span>ERROR<span class="token punctuation">]</span> NG8008: Required input <span class="token string">'name'</span> from component ChildComponent must be specified.
</code></pre></div>
<h2 id="input-with-setters-and-getters">@Input with setters and getters</h2>
<p>Now let's start diving into some of the lesser-known features of @Input, starting with getters and setters.</p>
<p>Besides applying the <code>@Input</code> decorator to member variables, we can also apply it to a getter:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token keyword">private</span> myCourses<span class="token operator">:</span> Course<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">get</span> <span class="token function">courses</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>myCourses<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">set</span> <span class="token function">courses</span><span class="token punctuation">(</span>courses<span class="token operator">:</span> Course<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// you can add here some logic to modify the courses input variable, and create a derived value</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>myCourses <span class="token operator">=</span> courses<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This can be useful in situations where you want to apply some sort of transformation to the value passed to the component.</p>
<p>In an upcoming section, we are going to show a better way of transforming input values.</p>
<p>But let's first finish our coverage of getter inputs.</p>
<p>In the above code, we have defined a component input property called <code>courses</code>, that uses internally a member variable called <code>myCourses</code>.</p>
<p>Here is how we can set the value of this input in a parent component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child [courses]="parentCourses"/> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>

    parentCourses <span class="token operator">:</span> Course<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token comment">// some initial value</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that it's not possible to set the value of the <code>myCourses</code> property on the parent component.</p>
<p>You might be wondering how the name of the input property (<code>courses</code>) was determined.</p>
<p>This was determined based on the name of the getter function, which is also called <code>courses</code>.</p>
<h2 id="input-with-aliases">@Input with aliases</h2>
<p>It's also possible to define the name of the input property explicitly, by defining an input alias.</p>
<p>Here is how to do it using a simplified notation:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token string">"userName"</span><span class="token punctuation">)</span> name<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In the above code, the <code>name</code> input property is aliased to <code>userName</code>.</p>
<p>With the alias in place, this is how you can set the property in a parent component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child [userName]="name" /></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>
  name <span class="token operator">=</span> <span class="token string">"John Doe"</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that if you are using the alias option in combination with other input options, you can also define your alias using the <code>@Input</code> configuration object:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    alias<span class="token operator">:</span> <span class="token string">"userName"</span><span class="token punctuation">,</span>
    required<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  name<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<h2 id="input-transforms">@Input transforms</h2>
<p>As we have mentioned, a better alternative to using input getters and setters is to instead use input transforms.</p>
<p>With input transforms we can easily modify the value of an input value before assigning it to the property of the component, essentially achieving the same effect as what we just did by using a setter.</p>
<p>This is done by using the <code>transform</code> property of the <code>@Input</code> decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token function-variable function">transform</span><span class="token operator">:</span> <span class="token punctuation">(</span>value<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token operator">=></span> value<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  name<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>With this transform in place, any string passed to the name input will be converted to upper case instantly.</p>
<p>Points to know when creating an input transform:</p>
<ul>
<li>Transform function should be pure. This means that the function should not have side effects.</li>
<li>Transform functions should be fast, they should not contain heavy calculations.</li>
<li>Transform functions cannot be set conditionally, but you can add logical conditions inside the function if you need to.</li>
</ul>
<h2 id="built-in-input-transforms-booleanattribute-and-numberattribute">Built-in input transforms booleanAttribute and numberAttribute</h2>
<p>Besides allowing us to replace the use of getters and setters, input transforms also come in handy to support common use cases like boolean or constant numeric properties.</p>
<p>Angular provides us with two built-in input transforms that are useful in many common scenarios: <code>booleanAttribute</code> and <code>numberAttribute</code>.</p>
<p>These transforms can help to make our templates more readable in certain situations.</p>
<p>For example, sometimes we might want to create a boolean input property such as a disabled flag:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  disabled<span class="token operator">:</span> <span class="token builtin">boolean</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>But the problem with this is that to set this flag, we need to use an input expression (using []) in the parent component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child [disabled]="true" /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>This works, but wouldn't it be much more convenient if we could set the disabled flag like this instead:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child disabled /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>This is just a small detail, but it does feel a lot more natural to the users of your component.</p>
<p>In this example, the mere presence of the disabled attribute indicates that the disabled property should be set to true.</p>
<p>I think that this makes the code look more readable, it looks much more just like plain HTML.</p>
<p>By default, this simplified syntax without using a [] expression wouldn't work as expected.</p>
<p>But we can make this work by applying the <code>booleanAttribute</code> input transform:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ name }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    transform<span class="token operator">:</span> booleanAttribute<span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  disabled<span class="token operator">:</span> <span class="token builtin">boolean</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Now our disabled input property works as expected: the mere presence of the disabled property (even without a value) will cause the disabled property to be true, or false otherwise.</p>
<p>Notice that if you need to use a [] expression to set this propertly dynamically, everything will still work correctly.</p>
<h2 id="the-numberattribute-built-in-input-transform">The numberAttribute built-in input transform</h2>
<p>Let's now look at <code>numberAttribute</code>, which is another built-in input transform.</p>
<p>The <code>numberAttribute</code> transform converts the string value of the input into a numeric value:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ age }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token decorator"><span class="token at operator">@</span><span class="token function">Input</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    transform<span class="token operator">:</span> numberAttribute<span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
  age<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>With this transform in place, we can now set the age property in the following way:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child age="20" /></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>Any string that we set as the age property will be automatically converted to a number, or to <code>NaN</code> if the conversion is not possible.</p>
<p>If we didn't have this transform in place, we would have to use a slightly more verbose syntax:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child [age]="20" /></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>This would also work, but it just feels a bit overkill just to set a simple number constant.</p>
<p>Using a transform makes our parent component template a bit easier to read, and makes it look closer to plain HTML.</p>
<h2 id="input-vs-attribute-what-are-the-differences">@Input vs @Attribute: what are the differences?</h2>
<p>Another decorator that you might come across that looks very similar to @Input is the @Attribute decorator.</p>
<p>The @Attribute decorator has usually been used to support certain use cases, most of which I think are now better handled via a transform.</p>
<p>The two decorators may look similar, but they are meant to be used for very different purposes.</p>
<p>To understand why both decorators exist, it's important to bear in mind how the DOM works in general.</p>
<p>Let's remember that a DOM element has two different sets of key-value pairs:</p>
<ul>
<li>
<p>DOM attributes: These are the HTML markup attributes, they are always strings, and they <em>don't</em> change their value over time.</p>
</li>
<li>
<p>DOM properties: These are the properties of the actual DOM node, so they can be of any type, not just a string. Also, properties change over time, just like the property of any Javascript object.</p>
</li>
</ul>
<p>Notice that there are certain property/attribute pairs that the DOM automatically keeps in sync, like the value property.</p>
<p>But that is <em>not</em> the case by default. In general, you can have a DOM property and a DOM attribute with the same name, and they will <em>not</em> be kept in sync.</p>
<h3 id="how-to-use-attribute">How to use @Attribute</h3>
<p>Most of the time when using a framework like Angular, we are always using DOM properties and <em>not</em> attributes.</p>
<p>We rarely need to deal directly with DOM attributes in the context of a web framework, but they are still a fundamental part of the DOM.</p>
<p>So just in case we ever need to do so, Angular has provided us with a decorator to grab the string value of an attribute:</p>
<p>Here is an example of how to use @Attribute:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-child"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;p>{{ age }}&lt;/p> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ChildComponent</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token decorator"><span class="token at operator">@</span><span class="token function">Attribute</span></span><span class="token punctuation">(</span><span class="token string">"age"</span><span class="token punctuation">)</span> <span class="token keyword">public</span> age<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the @Attribute decorator is meant to be used in the constructor only.</p>
<p>Here is how we can set the attribute:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;app-child age="10" /> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>This will inject the string &quot;10&quot; in the constructor of the child component.</p>
<p>This value is constant and won't change over time, as it's a DOM attribute.</p>
<p>So if you ever need by some reason to grab the value of a DOM attribute, this is how we can do it in Angular.</p>
<h2 id="when-to-use-input-vs-attribute">When to use @Input vs @Attribute?</h2>
<p>In general, we should rely on properties and not DOM attributes, so for the vast majority of situations you should always use @Input.</p>
<p>If what you were looking for to do with @Attribute was mostly to support a simplified syntax for boolean and numeric values, you can use input transforms instead as we have seen.</p>
<p>With the introduction of input transforms, I think that there are now fewer situations where you would need the @Attribute decorator.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this come out covering Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>@Input</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we explored the <code>@Input</code> decorator in detail, covering all its currently available options.</p>
<p>One of the most interesting options is the input transforms feature, which allows us to make our templates more readable by supporting common use cases like boolean or constant numeric properties.</p>
<p>Input transforms make the use of input getters/setters and the use of @Attribute decorator less necessary than before.</p>
<p>Transforms are a very convenient feature, so I encourage you to start using them in your templates.</p>
<p>If you have any questions or comments, let me know in the comment section below. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Standalone Components: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-standalone-components/</link>
      <guid isPermaLink="false">65761d40d5cd730001d936b8</guid>
      <pubDate>Mon, 11 Dec 2023 08:19:01 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to Angular standalone components. Learn why they are way better than regular components, and how to easily upgrade to them.</description>
      <content:encoded><![CDATA[<p>The main benefit of standalone components in Angular is probably not what you think it is.</p>
<p>In this guide we are going to learn everything about standalone components, and how they are better than NgModule-based components.</p>
<p>We are going to lay out in our next sections all the advantages of standalone components, an explain why some of their perceived disadvantages aren't that big of a problem after all.</p>
<p>We are also going to learn how standalone components can help make your application much faster, with minimal refactoring.</p>
<p>We will also look at how you can easily migrate your application to standalone components, and start reaping all these benefits.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>What are standalone components?</li>
<li>Using standard directives in standalone components</li>
<li>Why Standalone Components?</li>
<li>So what is the main practical benefit of standalone components?</li>
<li>Standalone Pipes</li>
<li>Standalone Directives</li>
<li>Using standalone components in NgModule-based components</li>
<li>Using NgModule-based components in standalone components</li>
<li>Lazy loading with standalone components</li>
<li>Application bootstrapping with standalone components</li>
<li>Easily migrating to standalone components</li>
<li>Summary</li>
</ul>
<p><strong>Note</strong>: Looking to learn more about other Angular core features like standalone components? Have a look at my other articles on <a href="https://blog.angular-university.io/tag/angular-core/">Angular Core</a>.</p>
<p>Let's first show a couple of standalone components, and then talk about their advantages right after this quick introduction.</p>
<h2 id="what-are-standalone-components">What are Standalone Components?</h2>
<p>Standalone components are a new type of Angular component that does not need to be declared in a <code>NgModule</code>.</p>
<p>These are components that can be used directly in the template of another component without being part of an NgModule, or imported in an NgModule.</p>
<p>Before diving into the advantages of standalone components, let's first see how they compare with regular components.</p>
<p>Here is a plain regular component, that is <em>not</em> standalone:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"hello"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Hello {{ name }}</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">HelloComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Regular components like this one <em>must</em> be declared in a NgModule, otherwise, they just can't be used in the template of another component.</p>
<p>In this case, we are going to import it into our main application module:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">NgModule</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  declarations<span class="token operator">:</span> <span class="token punctuation">[</span>AppComponent<span class="token punctuation">,</span> HelloComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BrowserModule<span class="token punctuation">,</span> FormsModule<span class="token punctuation">]</span><span class="token punctuation">,</span>
  providers<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  bootstrap<span class="token operator">:</span> <span class="token punctuation">[</span>AppComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppModule</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Now let's turn the HelloComponent into a standalone component!</p>
<p>For that, all we have to do is add the property <code>standalone: true</code> in its <code>@Component</code> decorator:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"hello"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Hello {{ name }}</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">HelloComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>And that's it!</p>
<p>Now to use this component, we simply have to import it into the component where we want to use it.</p>
<p>For example, let's say that we want to use the HelloComponent in the ParentComponent:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"parent"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;hello>&lt;/hello></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>HelloComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ParentComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we just have to import it in the imports array, and that's it!</p>
<p>These manual imports might seem like they would be cumbersome to maintain, but that is not the case, more on that later.</p>
<p>Notice that without the import, the ParentComponent will not work as intended, and often there won't be an error thrown.</p>
<h2 id="using-standard-directives-in-standalone-components">Using standard directives in Standalone Components</h2>
<p>Angular made most of its built-in directives available as standalone directives.</p>
<p>To use them in standalone components we need to add them to the <code>imports</code> array of the component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> NgClass <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-hello"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;div [ngClass]="{ highlight: true }">Hello World!&lt;/div> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>NgClass<span class="token punctuation">]</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">StandaloneComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Here we have imported the ngClass directive in the <code>imports</code> array of the<br>
<code>StandaloneComponent</code> component so that we can use it in the template.</p>
<p>Without this import, the component wouldn't work as intended.</p>
<p>Again, this manual import could be seen as a nuisance, more on that in the next section.</p>
<h2 id="why-standalone-components">Why Standalone Components?</h2>
<p>As you can see, standalone components are at first sight not that catchy at all!</p>
<p>You remove the concept of NgModule, but replace it with manual imports.</p>
<p>So why are they so much better than regular components?</p>
<p>There are several reasons.</p>
<h3 id="improved-developer-experience">improved developer experience</h3>
<p>The main reason why standalone components were introduced in Angular was to remove the notion of NgModules from the developer experience.</p>
<p>The concept of a module in Angular seemed unnecessary and made it a bit harder for beginners to learn Angular from scratch.</p>
<p>It was one extra concept to learn, and it was not clear why it was needed.</p>
<p>To solve this problem, Angular introduced standalone components.</p>
<p>Now with standalone components, you can create your components without having to declare them in any module, which is <em>much</em> more convenient.</p>
<h3 id="manual-imports-are-not-really-a-problem">Manual imports are not really a problem</h3>
<p>When they were first introduced, standalone components came with the drawback that you had to manually import any dependencies that the component needed directly in the component.</p>
<p>So even the core directives like ngClass or ngStyle have to be imported manually in each standalone component, as we have seen.</p>
<p>This was initially seen as problematic because all those manual imports are also a pain to maintain.</p>
<p>After all, one of the advantages of NgModules was that you could import a dependency in only one place inside the module, right?</p>
<p>So for a brief moment, we thought that standalone components would be cumbersome to use at the application level, due to constantly having to import everything, which doesn't sound practical.</p>
<p>It wasn't apparent what tangible benefits standalone components brought to the table when building applications.</p>
<p>So there didn't seem to be a compelling enough reason to migrate existing applications to them.</p>
<p>But nothing could be further from the truth!</p>
<p>Regarding the imports issue, nowadays any IDE can import all the dependencies of a standalone component automatically, thanks to the Angular Language Service.</p>
<p>The manual imports are no longer a pain, and you hardly notice them at all. The whole experience is seamless.</p>
<p>It just works.</p>
<h2 id="so-what-is-the-main-practical-benefit-of-standalone-components">So what is the main practical benefit of standalone components?</h2>
<p>Removing NgModules is not even the main benefit of standalone components, or the main reason to migrate an established application to them.</p>
<p>For me, the main benefit of standalone components is that they make it super easy to develop a fully lazy-loaded application, or migrate an existing monolithic application and make it fully lazy-loaded.</p>
<p>If you have been using NgModule components for a while, you likely noticed the following:</p>
<p>Your application developed with NgModules is probably relatively monolithic, even though NgModules are supposed to help you modularize your application.</p>
<p>And it's hard to refactor an existing large application to use lazy-loading if you haven't done it enough from the start.</p>
<p>If you did use lazy-loading, you probably only have a few lazy-loaded modules, but each module still contains a lot of screens.</p>
<p>So your application is probably not using lazy-loading to its full potential, because of the overhead caused by having to create a separate module per screen.</p>
<p>But what if I told you that if you switch to standalone components, that will make it trivial for you to take your semi-monolithic application and turn it into a fully lazy-loaded application in no time?!</p>
<p>Even if your application was not built with lazy loading in mind, and even if you have not created enough lazy loaded modules yet, it doesn't matter.</p>
<p>All you have to do is to use the Angular CLI to migrate to standalone components, make a few minor changes in your routing configuration using the new loadComponent option, and voila:</p>
<p>Every single screen of your application is now lazy loaded and is offloaded to a separate screen bundle, and your application is all of a sudden <em>much</em> faster!</p>
<p>So for me, that was the killer feature that made me decide to spend the time and resources to switch everything to standalone components, and my team never looked back.</p>
<p>Our main application bundle was reduced to less than half, thanks to a refactoring that took us less than a day for a quite large application, and every single screen is now lazy-loaded.</p>
<p>In a nutshell, besides removing extra concepts from the framework and making it more beginner-friendly, I find that:</p>
<blockquote>
<p>The main benefit of standalone components is that they make it trivial to develop a fully lazy-loaded application, or migrate an existing application and make it fully lazy-loaded.</p>
</blockquote>
<p>In the next few sections, we are going to see how to lazy-load standalone components.</p>
<p>But before that, let's see what other types of constructs besides components can be made standalone.</p>
<h2 id="standalone-pipes">Standalone Pipes</h2>
<p>Just like components, we can also create standalone pipes.</p>
<p>The process is very similar to standalone components, we just have to add the standalone flag:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Pipe</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token operator">:</span> <span class="token string">"capitalise"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CapitalisePipe</span> <span class="token keyword">implements</span> <span class="token class-name">PipeTransform</span> <span class="token punctuation">{</span>
  <span class="token function">transform</span><span class="token punctuation">(</span>word<span class="token operator">:</span> <span class="token builtin">string</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> word<span class="token punctuation">.</span><span class="token function">toLocaleUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This pipe is now standalone, so all we have to do is import it into the component where we want to use it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-hello"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Hello {{ name | capitalise }}</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CapitalisePipe<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>And just like pipes, we can also create standalone directives.</p>
<h2 id="standalone-directives">Standalone Directives</h2>
<p>Here is an example of a standalone directive:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Directive</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"[example-directive]"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleDirective</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>To use it, we just have to import it into another component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-hello"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
  &lt;div example-directive>Hello {{ name | capitalise }}&lt;/div></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>CapitalisePipe<span class="token punctuation">,</span> ExampleDirective<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">StandaloneComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the process is very similar to standalone components and pipes.</p>
<p>Notice that so far, we have just been showing examples of how to use standalone components, directives, and pipes inside other standalone components.</p>
<p>But don't worry, if you need to use standalone elements in NgModule-based components, you can do that as well.</p>
<p>There is <strong>full interoperability in both directions</strong>. Let's have a look at what this interoperability looks like.</p>
<h2 id="using-standalone-components-in-ngmodule-based-components">Using Standalone Components in NgModule-based Components</h2>
<p>Standalone components can also be used in NgModule-based components, just like any other component.</p>
<p>To use a standalone component within a NgModule-based application, you just need to import the standalone component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">NgModule</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  declarations<span class="token operator">:</span> <span class="token punctuation">[</span>
    AppComponent<span class="token punctuation">,</span>
    StandaloneComponent
  <span class="token punctuation">]</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>BrowserModule<span class="token punctuation">]</span><span class="token punctuation">,</span>
  providers<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  bootstrap<span class="token operator">:</span> <span class="token punctuation">[</span>AppComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppModule</span> <span class="token punctuation">{</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, it's very simple to use standalone components in module-based applications.</p>
<p>But what about the other way around?</p>
<h2 id="using-ngmodule-based-components-in-standalone-components">Using NgModule-based Components in Standalone Components</h2>
<p>We can also easily use NgModule-based components inside a standalone component.</p>
<p>Let's see how it's done.</p>
<p>First, we create a NgModule and export the NgModule-based component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">NgModule</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  declarations<span class="token operator">:</span> <span class="token punctuation">[</span>TraditionalComponent<span class="token punctuation">]</span><span class="token punctuation">,</span>
  <span class="token comment">// export the NgModule-based component</span>
  exports<span class="token operator">:</span> <span class="token punctuation">[</span>TraditionalComponent<span class="token punctuation">]</span><span class="token punctuation">,</span> 
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">MyModule</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>We then import the NgModule in the standalone component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app-standalone"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">I'm a standalone component 😁</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  <span class="token comment">// Import the NgModule that declares the component</span>
  imports<span class="token operator">:</span> <span class="token punctuation">[</span>MyModule<span class="token punctuation">]</span><span class="token punctuation">,</span> 
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">StandaloneComponent</span> <span class="token punctuation">{</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Now, the NgModule-based components can be used within the standalone component's template just like any other component.</p>
<p>Notice that because we imported the whole MyModule, any other components that are part of the public API of the imported module can also be used in the standalone component.</p>
<p>As you can see, the interoperability between Ng-Module components and standalone components is seamless.</p>
<p>We can easily mix and match the two types of components in our application, without any problem.</p>
<h2 id="lazy-loading-with-standalone-components">Lazy Loading with Standalone Components</h2>
<p>Lazy-loading just got a whole lot easier with the introduction of standalone components.</p>
<p>At first, without standalone components, lazy loading was done via modules.</p>
<p>We had to create a module for a set of components, pipes, or directives that we wanted to lazy load.</p>
<p>This was time-consuming, and involved a lot of boilerplate:</p>
<ul>
<li>creating the lazy loaded module</li>
<li>import all the dependencies manually</li>
<li>configure the module in the router</li>
</ul>
<p>Here is an example of what the routing configuration of a lazy-loaded module looks like:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">const</span> routes<span class="token operator">:</span> Routes <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">"one"</span><span class="token punctuation">,</span>
    <span class="token function-variable function">loadChildren</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span>
      <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">"./module-one/moduleone.module"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
      <span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span>m<span class="token punctuation">)</span> <span class="token operator">=></span> m<span class="token punctuation">.</span>ModuleOneModule<span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre></div>
<p>The overhead of lazy-loading modules does not come from the routing configuration itself.</p>
<p>It comes from the need to have to create a module and define all it's dependencies, not because we want to encapsulate certain features and make them reusable, but just for the single purpose of lazy-loading that content.</p>
<p>With standalone components, on the other hand, lazy loading is <em>much</em> easier:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">export</span> <span class="token keyword">const</span> <span class="token constant">ROUTES</span><span class="token operator">:</span> Route<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span>
  <span class="token punctuation">{</span>
    path<span class="token operator">:</span> <span class="token string">"lazy-hello"</span><span class="token punctuation">,</span>
    <span class="token function-variable function">loadComponent</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span>
      <span class="token keyword">import</span><span class="token punctuation">(</span><span class="token string">"./app-hello"</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span>m<span class="token punctuation">)</span> <span class="token operator">=></span> m<span class="token punctuation">.</span>StandaloneComponent<span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">]</span><span class="token punctuation">;</span>
</code></pre></div>
<p>All we have to do now is use the loadComponent option and point to the top-level container component of the route, and that's it!</p>
<p>We <em>don't</em> have to create a module per lazy-loaded screen anymore, and import all the dependencies that each screen needs every time.</p>
<p>So wih standalone components, lazy-loading is not a pain anymore, it's now become trival and it's much easier to use.</p>
<h2 id="application-bootstrapping-with-standalone-components">Application Bootstrapping with Standalone Components</h2>
<p>To take full advantage of standalone components, it's recommended to bootstrap the application using standalone APIs instead of NgModules:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">import</span> <span class="token punctuation">{</span> bootstrapApplication <span class="token punctuation">}</span> 
 <span class="token keyword">from</span> <span class="token string">"@angular/platform-browser"</span><span class="token punctuation">;</span>

<span class="token function">bootstrapApplication</span><span class="token punctuation">(</span>StandaloneComponent<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>In the <code>bootstrapApplication</code> API, we just need to pass a standalone component that we want to turn into the root of the application.</p>
<p>We can also import any dependencies that we need, like the router, forms, etc. using standalone APIs.</p>
<h2 id="migrating-to-standalone-components">Migrating to Standalone Components</h2>
<p>You can migrate your application to standalone components automatically using the Angular CLI.</p>
<p>You may still have to do some minor refactorings, but the CLI will do most of the work for you.</p>
<p>The migration happens in 3 separate steps. I recommend that you do them on a branch and create 3 separate commits.</p>
<p>For each step, you will need to run the following command each time:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng generate @angular/core:standalone
</code></pre></div>
<p>Here are the 3 steps:</p>
<p><strong>Step 1:</strong> Run the migration and select the &quot;Convert all components, directives, and pipes to standalone&quot; option. This will add the standalone flag everywhere, and populate the imports array of each component.</p>
<p><strong>Step 2:</strong> Run the migration again, but this time select the &quot;Remove unnecessary NgModule classes&quot; option. This will attempt to remove as many NgModules as possible, but it will likely not be able to remove them all, so you will have to review the code here and manually remove any modules that you can.</p>
<p><strong>Step 3:</strong> Run the migration one last time and select the &quot;Bootstrap the application using standalone APIs&quot; option.</p>
<p>This will remove the use of the AppModule to bootstrap the application, and it will use standalone APIs instead.</p>
<p>This last step is critical to be able to benefit the most from standalone components. For example, if you don't do this last step, component-based lazy loding with loadComponent won't work properly.</p>
<p>Test the application after each step, and commit the changes separately so that you can roll back to the previous step if something goes wrong.</p>
<p>In my experience, the migration will go smoothly, but you will likely still have to do some minor changes yourself to fully remove all NgModules from the codebase.</p>
<p>From there, just go to your routing configuration, and everywhere you see the option <code>component</code>, replace it with <code>loadComponent</code> and that's it!</p>
<p>All of a sudden you have gone from a semi-monolithic application to a fully lazy-loaded application, and your application feels way faster.</p>
<p>I hope that you enjoyed this post, to get notified when new similar Angular posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>If you want a deep dive into all the features of Angular Core like standalone components and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>.</p>
<p>We have a full section dedicated to standalone components, and how to migrate to them:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>Taking the time to migrate your application to standalone components is definitely worth it.</p>
<p>Switching to standalone components is not just about removing one extra concept from your codebase and preparing yourself for future versions of Angular.</p>
<p>Standalone components also provide some immediate very tangible benefits, especially when it comes to making it much easier to systematically use lazy-loading in your application.</p>
<p>The automated Angular CLI migration will do most of the work for you.</p>
<p>The manual imports are not an issue thanks to the Angular Language Service, and the whole developer experience is seamless.</p>
<p>Go ahead and try it out, and let me know in the comments below of any questions you might have!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Signals: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-signals/</link>
      <guid isPermaLink="false">6570f6fd9eefaf00010b4196</guid>
      <pubDate>Thu, 07 Dec 2023 09:38:18 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide on how to use Signals in an Angular application. Learn signals, their benefits, best practices, and patterns, and avoid the most common pitfalls.</description>
      <content:encoded><![CDATA[<p>Angular Signals were originally introduced in Angular 17, and they are really powerful.</p>
<p>The whole goal of signals is to give developers a new <strong>easy-to-use reactive primitive</strong> that can be used to build applications in reactive style.</p>
<p>Signals have an easy-to-understand API for reporting data changes to the framework, allowing the framework to optimize change detection and re-rendering in a way that so far was just not possible.</p>
<p>With Signals, Angular will be able to determine exactly what parts of the page need to be updated and update only those and nothing more.</p>
<p>This comes in contrast with what currently happens with for example default change detection, where Angular has to check all the components on the page, even if the data that they consume didn't change.</p>
<p>Signals are all about enabling very <strong>fine-grained updates to the DOM</strong> that are just not possible with the current change detection systems that we have available.</p>
<p>Signals are all about increasing the runtime performance of your application, by getting rid of Zone.js.</p>
<p>Even without the runtime performance benefits, signals are just a great way to build applications in reactive style in general.</p>
<p>Signals are also <strong>way easier to use and understand than RxJS</strong> when it comes to propagating data changes throughout an application.</p>
<p>Signals are a game changer, and they take reactivity in Angular to a whole new level!</p>
<p>In this guide, we will explore the Signals API in detail, explain how signals work in general, as well as talk about the most common pitfalls that you should watch out for.</p>
<blockquote>
<p><strong>Note:</strong> Signals are not yet plugged into the Angular change detection system.At this point, even though most of the Signals API is already out of developer preview, there aren't <em>yet</em> any signal-based components.<br>
This could be available around Angular 17.2, to be confirmed.<br>
But that doesn't prevent us from already starting to learn right now about signals and their advantages, in preparation for what is to come very soon.</p>
</blockquote>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post covers the following topics:</p>
<ul>
<li>What are Signals?</li>
<li>How to read the value of a signal?</li>
<li>How to modify the value of a signal?</li>
<li>The update() Signal API</li>
<li>What is the main advantage of using signals instead of primitive values?</li>
<li>The computed() Signal API</li>
<li>How do we subscribe to a signal?</li>
<li>Can we read the value of a signal from a computed signal without creating a dependency?</li>
<li>What is the major pitfall to look out for when creating computed signals?</li>
<li>Are signal dependencies determined based only on the initial call to the compute function?</li>
<li>Signals with array and object values</li>
<li>Overriding the signal equality check</li>
<li>Detecting signal changes with the effect() API</li>
<li>What is the relation between Signals and change detection?</li>
<li>How to fix the error NG0600: Writing to signals is not allowed</li>
<li>How to set signals from inside an effect, if needed</li>
<li>The default effect clean-up mechanism</li>
<li>How to clean up effects manually</li>
<li>Performing cleanup operations when an effect is destroyed</li>
<li>Read-only signals</li>
<li>Using a signal in multiple components</li>
<li>How to create signal-based reactive data services</li>
<li>Signals and OnPush components</li>
<li>Can I create signals outside of components/stores/services?</li>
<li>How do Signals compare to RxJs?</li>
<li>Summary</li>
</ul>
<p><strong>Note</strong>: If you are looking to learn about other Angular features besides signals, check out the following posts:</p>
<ul>
<li><a href="https://blog.angular-university.io/angular-if/">Angular @if: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-for/">Angular @for: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-switch/">Angular @switch: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-defer/">Angular @defer: Complete Guide</a></li>
</ul>
<p>And if you are looking to learn about signals in general, check out:</p>
<ul>
<li><a href="https://blog.angular-university.io/angular-signal-inputs/">Angular Signal Inputs: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-linkedsignal/">Angular linkedSignal: The Missing Link in Signal-Based Reactivity</a></li>
</ul>
<h2 id="what-are-signals">What are Signals?</h2>
<p>Simply put, a signal is a reactive primitive that represents a value and that allows us to change that same value in a controlled way and track its changes over time.</p>
<p>Signals are not a new concept exclusive to Angular. They have been around for years in other frameworks, sometimes under different names.</p>
<p>To better understand signals, let's start with a simple example that does not use signals yet, and then re-write the same example using the Signals API.</p>
<p>To start, let's say that we have a simple Angular component with a counter variable:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

&lt;h1>Current value of the counter {{counter}}&lt;/h1>

&lt;button (click)="increment()">Increment&lt;/button>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter<span class="token operator">:</span> <span class="token builtin">number</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, this is a very simple component.</p>
<p>It just displays a counter value, and it has a button to increment the counter. This component uses the Angular default change detection mechanism.</p>
<p>This means that the <code>{{counter}}</code> expression as well as any other expressions on the page are being checked for changes after each event, such as a click on the increment button.</p>
<p>As you can imagine, that could be a potentially ineffective way to try to detect what needs to be updated on the page.</p>
<p>In the case of our component, this approach is actually even necessary, because we are using a mutable plain Javascript member variable like <code>counter</code> to store our state.</p>
<p>So when an event occurs, just about <strong>anything</strong> on the page could have affected that data.</p>
<p>Furthermore, the click on the increment button could have easily triggered changes <em>anywhere else</em> on the page as well, and not just inside this component.</p>
<p>Imagine for example that we would call a shared service that would affect multiple parts of the page.</p>
<p>With default change detection, there is no way for Angular to know exactly what has changed on the page, so that is why we cannot make any assumptions about what happened, and we need to check <strong>everything</strong>!</p>
<p>Because we have no guarantees of what could or could not have changed, we need to scan the whole component tree and all the expressions on every component.</p>
<p>With default change detection, there is no other way.</p>
<p>But here is where signals come to the rescue!</p>
<p>Here is the same simple example, but this time re-written using the Signals API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

&lt;h1>Current value of the counter {{counter()}}&lt;/h1>

&lt;button (click)="increment()">Increment&lt;/button>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

  counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">counter value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
    
  <span class="token punctuation">}</span>

  <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

    <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the signal-based version of our component doesn't look that much different.</p>
<p>The major difference is that we are now wrapping our counter value in a signal using the <code>signal()</code> API, instead of just using a plain <code>counter</code> Javascript member variable.</p>
<p>This signal represents the value of a counter, that starts at zero.</p>
<p>We can see that the signal acts like a container for the value that we want to keep track of.</p>
<h2 id="how-to-read-the-value-of-a-signal">How to read the value of a signal?</h2>
<p>The signal wraps the value that it represents, but we can get that value at any time just by calling the signal as a function, without passing it any arguments.</p>
<p>Notice the code on the constructor of the signal-based version of our AppComponent:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">counter value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

<span class="token punctuation">}</span>

</code></pre></div>
<p>As you can see, by calling <code>counter()</code>, we get back the value wrapped in the signal, which in this case would resolve to zero (the initial value of the signal).</p>
<h2 id="how-to-modify-the-value-of-a-signal">How to modify the value of a signal?</h2>
<p>There are a couple of different ways to change the value of a signal.</p>
<p>In our case, we are using the <code>set()</code> API in our implementation of the counter increment function:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

    <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token punctuation">}</span>
</code></pre></div>
<p>We can use the <code>set()</code> API to set any value that we need in the signal, as long as the value is of the same type as the initial value of the signal.</p>
<p>So in the case of our counter signal, we can only set numbers because the initial value of the signal was zero.</p>
<h2 id="the-update-signal-api">The update signal API</h2>
<p>Besides the <code>set()</code> API, we also have available the <code>update()</code> API.</p>
<p>Let's use it to re-write our counter increment function:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">  <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

    <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>counter <span class="token operator">=></span> counter <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the update API takes a function that receives the current value of the signal as an input argument, and then it returns the new value of the signal.</p>
<p>Both versions of the increment method are equivalent and work equally well.</p>
<h2 id="what-is-the-main-advantage-of-using-signals-instead-of-primitive-values">What is the main advantage of using signals instead of primitive values?</h2>
<p>At this point, we can now see that a signal is just a lightweight wrapper or a container for a value.</p>
<p>So what is the advantage of using it then?</p>
<p>The main advantage is that we can get notified when the signal value changes, and then do something in response to the new signal value.</p>
<p>This is unlike the case when we used just a plain value for our counter.</p>
<p>With a plain value, there is no way for us to get notified when a value changes.</p>
<p>But with Signals? Easy!</p>
<p>And that's the whole point of using signals in the first place.</p>
<h2 id="the-computed-signal-api">The <code>computed()</code> Signal API</h2>
<p>Signals can be created and derived from other signals. When a signal updates, all its dependent signals will then get updated automatically.</p>
<p>For example, let's say that we would like to have a derived counter on our component, that is the value of the counter multiplied by 10.</p>
<p>We can create a derived signal based on our counter signal, by using the<br>
<code>computed()</code> API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

  &lt;h3>10x counter: {{derivedCounter()}}&lt;/h3>

  &lt;button (click)="increment()">Increment&lt;/button>

    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    derivedCounter <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

        <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span><span class="token punctuation">)</span>

    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>The computed API works by taking in one or more source signals, and creating a new signal.</p>
<p>When the source signal changes (in our case the counter signal), the computed signal derivedCounter gets updated as well, instantly.</p>
<p>So when we click on the Increment button, the counter will have the initial value of 1 and the derivedCounter will be 10, then 2 and 20, 3 and 30, etc.</p>
<h2 id="how-do-we-subscribe-to-a-signal">How do we subscribe to a signal?</h2>
<p>Notice that the derivedCounter signal <em>did not subscribe</em> in any explicit way to the source counter signal.</p>
<p>The only thing that it did was call the source signal using <code>counter()</code> inside its computed function.</p>
<p>But that's all that we needed to do to link the two signals together!</p>
<p>Now whenever the counter source signal has a new value, the derived signal also gets updated automatically.</p>
<p>It all sounds kind of magical, so let's break down what is going on:</p>
<ul>
<li>Whenever we are creating a computed signal, the function passed to <code>computed()</code> is going to get called at least once, to determine the initial value of the derived signal</li>
<li>Angular is keeping track as the compute function is being called and takes note when other signals that it knows are being used.</li>
<li>Angular will notice that when the value of derivedCounter is being calculated, the signal getter function <code>counter()</code> is called.</li>
<li>So Angular now knows that there is a dependency between the two signals, so whenever the counter signal gets set with a new value, the derived <code>derivedCounter</code> will also be updated</li>
</ul>
<p>As you can see, this way the framework has all the information about what signals depend on other signals.</p>
<p>Angular knows the whole signal dependency tree and knows how changing the value of one signal will affect all the other signals of the application.</p>
<h2 id="can-we-read-the-value-of-a-signal-from-a-computed-signal-without-creating-a-dependency">Can we read the value of a signal from a computed signal without creating a dependency?</h2>
<p>There could be certain advanced scenarios where we want to read the value of a signal from another computed signal, but without creating any dependency between both signals.</p>
<p>This should be rarely needed, but if you ever run into a situation where you need to do this, here is how you do it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

  &lt;h3>10x counter: {{derivedCounter()}}&lt;/h3>

    </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    derivedCounter <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

        <span class="token keyword">return</span> <span class="token function">untracked</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>By using the untracked API, we can access the value of the counter signal without creating a dependency between the counter and the derivedCounter signal.</p>
<p>Notice that this untracked feature is an advanced feature that should be rarely needed, if ever.</p>
<p>If you find yourself using this feature very often, something is not right.</p>
<h2 id="what-is-the-major-pitfall-to-look-out-for-when-creating-computed-signals">What is the major pitfall to look out for when creating computed signals?</h2>
<p>For everything to work smoothly, we need to make sure that we compute our derived signals in a certain way.</p>
<p>Remember, Angular will only consider that one signal depends on another if it notices that a signal is needed to calculate the value of another signal.</p>
<p>This means that we need to be careful with introducing conditional logic inside the computed function.</p>
<p>Here is an example of how things could easily go wrong:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

  &lt;h3>Derived counter: {{derivedCounter()}}&lt;/h3>

  &lt;button (click)="increment()">Increment&lt;/button>

  &lt;button (click)="multiplier = 10">
    Set multiplier to 10
  &lt;/button>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    multiplier<span class="token operator">:</span> <span class="token builtin">number</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    derivedCounter <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>multiplier <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token number">0</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token keyword">this</span><span class="token punctuation">.</span>multiplier<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>

    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see in this example, there is some conditional logic in the compute function.</p>
<p>We are calling the <code>counter()</code> source signal like before, but only if a certain condition is met.</p>
<p>The goal of this logic would be to set the value of the multiplier dynamically, via some user action like clicking on the &quot;Set multiplier to 10&quot; button.</p>
<p>But this logic does <strong>not</strong> work as expected!</p>
<p>If you run it, the counter itself will still be incremented.</p>
<p>But the expression <code>{{derivedCounter()}}</code> will always be evaluated to zero, both before and after the &quot;Set multiplier to 10&quot; gets clicked.</p>
<p>The problem is that when we calculate the derived value, no calls to <code>counter()</code> are made initially.</p>
<p>The call to <code>counter()</code> is made inside an <code>else</code> branch, that does not get run initially.</p>
<p>So Angular does not know that there was a dependency between the counter signal and the derivedCounter signal.</p>
<p>Those are considered by Angular as two completely independent signals, without any connection.</p>
<p>This is why when we update the value of the counter, derivedCounter does not get updated.</p>
<p>This means that we need to be somewhat careful when defining computed signals.</p>
<p>If a derived signal depends on a source signal, we need to make sure we call the source signal every time that the compute function gets called.</p>
<p>Otherwise, the dependency between the two signals will be broken.</p>
<p>This does not mean that we can't have any conditional branching at all inside a compute function.</p>
<p>For example, the following code would work correctly:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

  &lt;h3>Derived counter: {{derivedCounter()}}&lt;/h3>

  &lt;button (click)="increment()">Increment&lt;/button>

  &lt;button (click)="multiplier = 10">
    Set multiplier to 10
  &lt;/button>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    multiplier<span class="token operator">:</span> <span class="token builtin">number</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    derivedCounter <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token number">0</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token keyword">this</span><span class="token punctuation">.</span>multiplier<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>

    <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Updating counter...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>With this version of the code, our compute function is now calling <code>this.counter()</code> in every call.</p>
<p>So Angular can now identify the dependency between the two signals, and the code works as expected.</p>
<p>This means that after clicking the &quot;Set multiplier to 10&quot; button the first time, the multiplier will be applied correctly.</p>
<h2 id="are-signal-dependencies-determined-based-only-on-the-initial-call-to-the-computed-function">Are signal dependencies determined based only on the initial call to the computed function?</h2>
<p>No, instead the dependencies of a derived signal are identified dynamically based on its last calculated value.</p>
<p>So with every new call of the computed function, the source signals of the computed signal are identified again.</p>
<p>This means that a signal's dependencies are dynamic, they are not fixed for the lifetime of the signal.</p>
<p>Again, this means that we need to be careful with any conditional logic that we create when defining a derived signal.</p>
<h2 id="signals-with-array-and-object-values">Signals with array and object values</h2>
<p>So far, we have been showing examples of a signal with a primitive type, like a number.</p>
<p>But what would happen if we define a signal whose value is an array or an object?</p>
<p>Arrays and objects work mostly the same way as primitive types, but there are just a couple of things to watch out for.</p>
<p>For example, let's take the case of a signal whose value is an array, and another signal whose value is an object:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>List value: {{list()}}&lt;/h3>

  &lt;h3>Object title: {{object().title}}&lt;/h3>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    list <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
        <span class="token string">"Hello"</span><span class="token punctuation">,</span>
        <span class="token string">"World"</span>
    <span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    object <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
       id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
       title<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">list</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token string">"Again"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>title <span class="token operator">=</span> <span class="token string">"overwriting title"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>There is nothing special about these signals, in the sense that we can access their values as usual just by calling the signal as a function.</p>
<p>But the key thing to notice is that unlike a primitive value, <strong>nothing prevents us from mutating the content</strong> of the array directly by calling push on it, or from mutating an object property.</p>
<p>So in this example, the output generated to the screen would be:</p>
<ul>
<li>&quot;Hello&quot;, &quot;World&quot;, &quot;Again&quot; in the case of the list</li>
<li>&quot;overwriting title&quot; in the case of the object title</li>
</ul>
<p>This is of course <em>not</em> how Signals are meant to be used!</p>
<p>Instead, we want to update the value of a signal by always using the <code>set()</code> and <code>update()</code> APIs.</p>
<p>By doing so, we give a change to all the derived signals for updating themselves and have those changes reflected on the page.</p>
<p>By directly accessing the signal value and mutating its value directly, we are bypassing the whole signal system and potentially causing all sorts of bugs.</p>
<p>It is worth keeping this in mind, we should avoid mutating signal values directly, and instead always use the Signals API.</p>
<p>This is worth mentioning because there is currently no protective mechanism in the Signals API for preventing this misuse, like preventively freezing the array or the object value.</p>
<h2 id="overriding-the-signal-equality-check">Overriding the signal equality check</h2>
<p>Another thing worth mentioning regarding array or object signals is that the default equality check is &quot;===&quot;.</p>
<p>This equality check is important because a signal will only emit a new value if the new value that we are trying to emit is different then the previous value.</p>
<p>If the value that we are trying to emit is considered to be the same as the previous value, then Angular will <em>not</em> emit the new signal value.</p>
<p>This is a performance optimization that potentially prevents unnecessary re-rendering of the page, in case we are systematically emitting the same value.</p>
<p>The default behavior however is based on &quot;===&quot; referential equality, which does not allow us to identify arrays or objects that are functionally identical.</p>
<p>If we want to do that, we need to override the signal equality function and provide our implementation.</p>
<p>To understand this, let's start with a simple example where we are still using the default equality check for a signal object.</p>
<p>Then we create a derived signal from it:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Object title: {{title()}}&lt;/h3>

  &lt;button (click)="updateObject()">Update&lt;/button>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    object <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
            title<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    title <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">Calling computed() function...</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>

        <span class="token keyword">const</span> course <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> course<span class="token punctuation">.</span>title<span class="token punctuation">;</span>

    <span class="token punctuation">}</span><span class="token punctuation">)</span>

    <span class="token function">updateObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

      <span class="token comment">// We are setting the signal with the exact same </span>
      <span class="token comment">// object to see if the derived title signal will </span>
      <span class="token comment">// be recalculated or not</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>object<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
        id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
        title<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>In this example, if we click on the Update button multiple times, we are going to get multiple logging lines in the console:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">Calling computed() function...
Calling computed() function...
Calling computed() function...
Calling computed() function...
etc.
</code></pre></div>
<p>This is because the default &quot;===&quot; cannot detect that we are passing to the object signal a value that is functionally equivalent to the current value.</p>
<p>Because of this, the signal will consider that the two values are different, and so any computed signals that depend on the object signal will also get computed.</p>
<p>If we want to avoid this, we need to pass our equality function to the signal:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">object <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span>
  <span class="token punctuation">{</span>
    id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
    title<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span>
    <span class="token function-variable function">equal</span><span class="token operator">:</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> a<span class="token punctuation">.</span>id <span class="token operator">===</span> b<span class="token punctuation">.</span>id <span class="token operator">&amp;&amp;</span> a<span class="token punctuation">.</span>title <span class="token operator">==</span> b<span class="token punctuation">.</span>title<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>With this equality function in place, we are now doing a deep comparison of the object based on the values of its properties.</p>
<p>With this new equality function, the derived signal is only computed once no matter how many times we click on the Update button:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">Calling computed() function...
</code></pre></div>
<p>It's worth mentioning that in most cases, we <em>shouldn't</em> provide this type of equality functions for our signals.</p>
<p>In practice, the default equality check works just fine, and using a custom equality check should rarely make any noticeable difference.</p>
<p>Writing this type of custom equality check could lead to maintainability issues and all sorts of weird bugs if for example we add a property to the object and forget to update the comparison function.</p>
<p>Equality functions are covered in this guide just for completeness in the rare case when you need them, but in general, for most use cases there is no need to use this feature.</p>
<h2 id="detecting-signal-changes-with-the-effect-api">Detecting signal changes with the effect() API</h2>
<p>The use of the computed API shows us that one of the most interesting properties of signals is that we can somehow detect when they change.</p>
<p>After all, that is exactly what the <code>computed()</code> API is doing, right?</p>
<p>It detects that a source signal has changed, and in response, it calculates the value of a derived signal.</p>
<p>But what if instead of calculating the new value of a dependent signal, we just want to detect that a value has changed for some other reason?</p>
<p>Imagine that you are in a situation where you need to detect that the value of a signal (or a set of signals) has changed to perform some sort of side effect, that does not modify other signals.</p>
<p>This could be for example:</p>
<ul>
<li>logging the value of a number of signals using a logging library</li>
<li>exporting the value of a signal to localStorage or a cookie</li>
<li>saving the value of a signal transparently to the database in the background</li>
<li>etc.</li>
</ul>
<p>All of these scenarios can be implemented using the <code>effect()</code> API:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">
<span class="token comment">//The effect will be re-run whenever any </span>
<span class="token comment">// of the signals that it uses changes value.</span>
<span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>

  <span class="token comment">// We just have to use the source signals </span>
  <span class="token comment">// somewhere inside this effect</span>
  <span class="token keyword">const</span> currentCount <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">const</span> derivedCounter <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">derivedCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">current values: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>currentCount<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> 
    </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>derivedCounter<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

</code></pre></div>
<p>This effect will print out a logging statement to the console anytime that the counter or derivedCounter signals emit a new value.</p>
<p>Notice that this effect function will run at least once when the effect is declared.</p>
<p>This initial run allows us to determine the initial dependencies of the effect.</p>
<p>Just like in the case of the <code>computed()</code> API, the signal dependencies of an effect are determined dynamically based on the last call to the effect function.</p>
<h2 id="what-is-the-relation-between-signals-and-change-detection">What is the relation between Signals and change detection?</h2>
<p>I think you can see where this is going...</p>
<p>Signals allow us to easily track changes to application data.</p>
<p>Now imagine the following: let's say we put <strong>all</strong> our application data inside signals!</p>
<p>The first point to mention is that the code of the application wouldn't become much more complicated because of that.</p>
<p>The Signals API and the signal concept are pretty straightforward, so a codebase that uses signals everywhere would remain quite readable.</p>
<p>Still, that application code wouldn't be as simple to read as if it was just using plain Javascript member variables for the application data.</p>
<p>So what is the advantage then?</p>
<p>Why would we want to switch to a signal-based approach for handling our data?</p>
<p>The advantage is that with signals, we can easily detect when any part of the application data changes, and update any dependencies automatically.</p>
<p>Now imagine that the Angular change detection is plugged into the signals of your application, and that Angular knows in which components and expressions every signal is being used.</p>
<p>This would enable Angular to know exactly what data has changed in the application, and what components and expressions need to be updated in response to a new signal value.</p>
<p>There would no longer be the need to check the whole component tree, like in the case of default change detection!</p>
<p>If we give Angular the guarantee that all the application data goes inside a signal, Angular all of a sudden has all the necessary information needed for doing the most optimal change detection and re-rendering possible.</p>
<p>Angular would know how to update the page with the latest data in the most optimal way possible.</p>
<p>And that is the main performance benefit of using signals!</p>
<p>Just by wrapping our data in a signal, we enable Angular to give us the most optimal performance possible in terms of DOM updates.</p>
<p>And with this, you now have a pretty good view of how signals work and why they are useful.</p>
<p>The question is now, how to use them properly?</p>
<h2 id="the-default-effect-clean-up-mechanism">The default effect clean-up mechanism</h2>
<p>An effect is a function that gets called in response to a change in a signal's value.</p>
<p>And like any function, it can create references to other variables in the application, via a closure.</p>
<p>This means that just like any function, we need to watch out for the potential of creating accidental memory leaks when using effects.</p>
<p>To help cope with this, Angular will by default automatically clean up the effect function, depending on the context where it was used.</p>
<p>So for example, if you create the effect inside a component, Angular will clean up the effect when the component gets destroyed, and the same goes for directives, etc.</p>
<h2 id="how-to-clean-up-effects-manually">How to clean up effects manually</h2>
<p>But sometimes, for some reason, you might want instead to clean up your effects manually.</p>
<p>This should only be necessary on rare occasions though.</p>
<p>If you are systematically cleaning up the effects manually everywhere in your application, something is likely not right.</p>
<p>But in case you need to, an <code>effect()</code> can be manually destroyed by calling<br>
<code>destroy</code> on the <code>EffectRef</code> instance that it returns when first created.</p>
<p>In those cases, you probably also want to disable the default cleanup behavior by using the <code>manualCleanup</code> option:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>

  count <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token keyword">const</span> effectRef <span class="token operator">=</span> <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">current value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token punctuation">{</span>
            manualCleanup<span class="token operator">:</span> <span class="token boolean">true</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// we can manually destroy the effect </span>
    <span class="token comment">// at any time</span>
    effectRef<span class="token punctuation">.</span><span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The <code>manualCleanup</code> flag disables the default cleanup mechanism, allowing us to have full control over when the effect gets destroyed.</p>
<p>The <code>effectRef.destroy()</code> method will destroy the effect, removing it from any upcoming scheduled executions, and cleaning up any references to variables outside the scope of the effect function, potentially preventing memory leaks.</p>
<h2 id="performing-cleanup-operations-when-an-effect-is-destroyed">Performing cleanup operations when an effect is destroyed</h2>
<p>Sometimes just removing the effect function from memory is not enough for a proper cleanup.</p>
<p>On some occasions, we might want to perform some sort of cleanup operation like closing a network connection or otherwise releasing some resources when an effect gets destroyed.</p>
<p>To support these use cases, we can pass to an effect a <code>onCleanup</code> callback function:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token operator">...</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>

  count <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

    <span class="token function">effect</span><span class="token punctuation">(</span><span class="token punctuation">(</span>onCleanup<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    
      <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">current value: </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>

      <span class="token function">onCleanup</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
        <span class="token builtin">console</span><span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"Perform cleanup action here"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This function will be called when the cleanup takes place.</p>
<p>Inside the <code>onCleanup</code> function, we can do any cleanup we want, such for example:</p>
<ul>
<li>unsubscribing from an observable</li>
<li>closing a network or database connection</li>
<li>clearing setTimeout or setInterval</li>
<li>etc.</li>
</ul>
<p>Let's now explore a few more signal-related concepts, and then show some common patterns that you are likely to need when using signals in your application.</p>
<h2 id="read-only-signals">Read-only signals</h2>
<p>We have already been using read-only signals already, even without noticing.</p>
<p>These are signals whose value can't be mutated. These are like the equivalent of <code>const</code> in the JavaScript language.</p>
<blockquote>
<p>Readonly signals can be accessed to read their value but can't be changed using the set or update methods. Read-only signals do <em>not</em> have any built-in mechanism that would prevent deep mutation of their value. - <a href="https://github.com/angular/angular/blob/main/packages/core/primitives/signals/README.md" target="_blank" rel="noopener">Angular repo</a></p>
</blockquote>
<p>Read-only signals can be created from:</p>
<ul>
<li><code>computed()</code></li>
<li><code>signal.asReadonly()</code></li>
</ul>
<p>Let's try to change the value of a derived signal, just to see what happens:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

  &lt;h3>Derived counter: {{derivedCounter()}}&lt;/h3>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    derivedCounter <span class="token operator">=</span> <span class="token function">computed</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">counter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">)</span>

    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token comment">// this works as expected</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// this throws a compilation error</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>derivedCounter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token number">50</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>As we can see, we can set new values for the counter signal, which is a normal writeable signal.</p>
<p>But we can't set values on the derivedCounter signal, as both the <code>set()</code> and<br>
<code>update()</code> APIs are unavailable.</p>
<p>This means that derivedCounter is a read-only signal.</p>
<p>If you need to, you can easily derive a read-only signal from a writeable signal:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span>
    selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
    template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">

  &lt;h3>Counter value {{counter()}}&lt;/h3>

</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>

    counter <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token keyword">const</span> readOnlyCounter <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">asReadonly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// this throws a compilation error</span>
        readOnlyCounter<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre></div>
<p>Notice that the other way around is not possible: you don't have an API to create a writeable signal from a read-only signal.</p>
<p>To do that, you would have to create a new signal with the current value of the read-only signal.</p>
<h2 id="using-a-signal-in-multiple-components">Using a signal in multiple components</h2>
<p>Let's now talk about some common patterns that you have available for using signals in your application.</p>
<p>If a signal is only used inside a component, then the best solution is to turn it into a member variable as we have been doing so far.</p>
<p>But what if the signal data is needed in several different places of the application?</p>
<p>Well, nothing prevents us from creating a signal and using it in multiple components.</p>
<p>When the signal changes, all the components that use the signal will be updated.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token comment">// main.ts</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> signal <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>

<span class="token keyword">export</span> <span class="token keyword">const</span> count <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div>
<p>As you can see, our signal is in a separate file, so we can import it in any component that needs it.</p>
<p>Let's create two components that use the <code>count</code> signal.</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token comment">// app.component.ts</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> Component <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"@angular/core"</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> count <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">"./main"</span><span class="token punctuation">;</span>

<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;div>
      &lt;p>Counter: {{ count() }}&lt;/p>
      &lt;button (click)="increment()">Increment from HundredIncrComponent&lt;/button>
    &lt;/div>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">HundredIncrComponent</span> <span class="token punctuation">{</span>
  count <span class="token operator">=</span> count<span class="token punctuation">;</span>

  <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token operator">=></span> value <span class="token operator">+</span> <span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here, we imported the <code>count</code> signal and used it in this component, and we could do the same with any other component in the application.</p>
<p>In some simple scenarios, this might very well be all that you need.</p>
<p>However, I think that for most applications, this approach will not be sufficient.</p>
<p>This is a bit like using a global mutable variable in Javascript.</p>
<p>Anyone can mutate it, or in the case of signals, emit a new value by calling<br>
<code>set()</code> on it.</p>
<p>I think that in most cases, this is not a good idea, for the same reasons that a global mutable variable is usually not a good idea.</p>
<p>Instead of giving unrestricted access to anyone to this signal, we want to make sure that the access to this signal is somehow encapsulated and kept under control.</p>
<h2 id="how-to-create-signal-based-reactive-data-services">How to create signal-based reactive data services</h2>
<p>The simplest pattern to share a writeable signal across multiple components is to wrap the signal in a data service, like so:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Injectable</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  providedIn<span class="token operator">:</span> <span class="token string">"root"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterService</span> <span class="token punctuation">{</span>

  <span class="token comment">// this is the private writeable signal</span>
  <span class="token keyword">private</span> counterSignal <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// this is the public read-only signal</span>
  <span class="token keyword">readonly</span> counter <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>counterSignal<span class="token punctuation">.</span><span class="token function">asReadonly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// inject any dependencies you need here</span>
  <span class="token punctuation">}</span>

  <span class="token comment">// anyone needing to modify the signal </span>
  <span class="token comment">// needs to do so in a controlled way</span>
  <span class="token function">incrementCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>counterSignal<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">=></span> val <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This pattern is very similar to the use of Observable Data Services with RxJs and a BehaviorSubject (see this <a href="https://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/">guide</a> on it), if you are familiar with that pattern.</p>
<p>The difference is that this service is much more straightforward to understand, and there are less advanced concepts at play here.</p>
<p>We can see that the writeable signal counterSignal is kept private from the service.</p>
<p>Anyone needing the value of the signal can get it via its public read-only counterpart, the counter member variable.</p>
<p>And anyone needing to modify the value of the counter can only do so in a controlled way, via the incrementCounter public method.</p>
<p>This way, any validations or error-handling business logic can be added to the method, and no one can bypass them.</p>
<p>Imagine that there is a rule that says that the counter cannot go above 100.</p>
<p>With this pattern, we can easily implement that on the incrementCounter method in one single place, rather than repeating that logic everywhere in the application.</p>
<p>We can also refactor and maintain the application better.</p>
<p>If we want to find out all parts of the application that are incrementing the counter, we just have to find the usage of the incrementCounter method using our IDE.</p>
<p>This type of code analysis would <em>not</em> be possible if we would just give direct access to the signal.</p>
<p>Also, if the signal needs access to any dependencies to work properly, those can be received in the constructor, like in any other service.</p>
<p>One of the principles at play here that makes this solution more maintainable is the principle of encapsulation.</p>
<p>We don't want just any part of the application to be able to emit freely new values for the signal, we want to allow that only in a controlled way.</p>
<p>So in general, if you have a signal shared across multiple components, for most cases you are probably better off using this pattern, rather than giving access to the writeable signal directly.</p>
<h2 id="signals-and-onpush-components">Signals and OnPush components</h2>
<p><code>OnPush</code> components are components that are only updated when their input properties change, or when Observables subscribed with the <code>async</code> pipe emit new values.</p>
<p>They are not updated when their input properties are mutated.</p>
<p>Now <code>OnPush</code> components are also integrated with signals.</p>
<p>When signals are used on a component, Angular marks that component as a dependency of the signal. When the signal changes, the component is re-rendered.</p>
<p>In the case of <code>OnPush</code> components, they will also be re-rendered when a signal attached to it is updated:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"counter"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;h1>Counter&lt;/h1>
    &lt;p>Count: {{ count() }}&lt;/p>
    &lt;button (click)="increment()">Increment&lt;/button>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  changeDetection<span class="token operator">:</span> ChangeDetectionStrategy<span class="token punctuation">.</span>OnPush<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">CounterComponent</span> <span class="token punctuation">{</span>
  count <span class="token operator">=</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token operator">=></span> value <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In this example, if we click on the Increment button, the component will be re-rendered, meaning that Signals are integrated directly with <code>OnPush</code>.</p>
<p>This means that we no longer need to inject <code>ChangeDetectorRef</code> and invoke<br>
<code>markForCheck</code>, to update an <code>OnPush</code> component in this scenario.</p>
<p>Consider the below example that does not use signals:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> Number: {{ num }} </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  changeDetection<span class="token operator">:</span> ChangeDetectionStrategy<span class="token punctuation">.</span>OnPush<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  num <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>

  <span class="token keyword">private</span> cdr <span class="token operator">=</span> <span class="token function">inject</span><span class="token punctuation">(</span>ChangeDetectorRef<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token function">ngOnInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">setInterval</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>num <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>num <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>cdr<span class="token punctuation">.</span><span class="token function">markForCheck</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, this is all a lot more complicated for the same equivalent functionality. The signal-based version is much simpler.</p>
<h2 id="can-i-create-signals-outside-of-components-stores-services">Can I create signals outside of components/stores/services?</h2>
<p>Absolutely! You can create signals anywhere you want. No constraint says that a signal needs to be inside a component, store, or service.</p>
<p>We demonstrated that earlier. That is the beauty and power of Signals. In most cases though, you probably want to wrap the signal in a service, as we have seen.</p>
<h2 id="how-do-signals-compare-to-rxjs">How do Signals compare to RxJs?</h2>
<p>Signals are not a direct replacement for RxJs, but they provide an easier-to-use alternative in certain situations where we would commonly need RxJs.</p>
<p>For example, signals are a great alternative to RxJS Behavior Subjects when it comes to transparently propagating data changes to multiple parts of the application.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>signals</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we explored the Angular Signals API and the concept of a new reactive primitive: the signal.</p>
<p>We have learned that by using signals to track all our application states, we are enabling Angular to easily know what parts of the view need to be updated.</p>
<p>In summary, the <strong>main goals</strong> of Signals are:</p>
<ul>
<li>providing a new reactive primitive that is easier to understand, to enable us to build applications in a reactive style much more easily.</li>
<li>avoiding unnecessary re-rendering of components that don't need to be re-rendered.</li>
<li>avoiding unnecessary checks of components whose data didn't change.</li>
</ul>
<p>The signals API is straightforward to use, but beware of some common pitfalls that you might run into:</p>
<ul>
<li>when defining effects or computed signals, be careful when reading the value of source signals inside conditional blocks</li>
<li>when using array or object signals, avoid mutating the signal value directly</li>
<li>don't overuse advanced features like providing your equality functions or doing manual effect cleanup unless it's necessary. The default behaviors should work just fine in the majority of cases.</li>
</ul>
<p>I invite you to try out Signals in your application, and see the magic for yourself!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @defer: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-defer/</link>
      <guid isPermaLink="false">65609e1b6d24f50001c35fbc</guid>
      <pubDate>Mon, 27 Nov 2023 13:51:15 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide on how to use the Angular @defer syntax for doing partial template loading, including all the predefined triggers, how to build custom triggers, and how it compares to lazy loading.</description>
      <content:encoded><![CDATA[<p>One of the most effective methods for improving the performance of a single-page application is to defer the loading of non-critical resources as much as possible.</p>
<p>Critical resources should be loaded first, while other <strong>less crucial resources should be loaded later</strong>, only when and <em>if</em> needed.</p>
<p>There is a good chance that a large portion of your code base is not needed for a typical user session.</p>
<p>So why load code that we are not 100% sure we will need? Loading unnecessary code just slows down our application.</p>
<p>Angular has had so far one major built-in mechanism for avoiding loading unnecessary resources: router-based lazy loading.</p>
<p>This mechanism is very powerful, but it has a limitation: it doesn't allow to lazy-load <em>parts</em> of a given template.</p>
<p>But what if you have a large screen with lots of dependencies, and you want to load parts of the page that are not immediately visible in the background, while you wait for the user to scroll down the page, or to click on a button?</p>
<p>This type of very fine-grained deferred loading is just not possible with router-based lazy loading.</p>
<p>But that is exactly where <code>@defer</code> comes in!</p>
<p><code>@defer</code> allows all of those scenarios and much more.</p>
<p>In this guide, we will explore how to use the <code>@defer</code> template syntax to take the performance of your Angular applications to the next level.</p>
<p>We will also explain its relation to lazy loading, and how it compares to it.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post covers the following topics:</p>
<ul>
<li>What is @defer, and why do we need it?</li>
<li>@defer in action</li>
<li>@defer with @placeholder</li>
<li>@placeholder parameters</li>
<li>@defer with @loading</li>
<li>The difference between @placeholder and @loading</li>
<li>@defer with @error</li>
<li>How do @defer triggers work?</li>
<li>The idle built-in trigger</li>
<li>The viewport built-in trigger with @placeholder</li>
<li>The viewport built-in trigger without @placeholder</li>
<li>The interaction built-in trigger with @placeholder</li>
<li>The interaction built-in trigger without @placeholder</li>
<li>The hover built-in trigger with@placeholder</li>
<li>The hover built-in trigger without @placeholder</li>
<li>The immediate built-in trigger</li>
<li>The timer built-in trigger</li>
<li>Prefetching @defer blocks</li>
<li>Prefetching on the viewport, displaying on interaction</li>
<li>Custom @defer triggers with the when keyword</li>
<li>What happens when @defer is used with server-side rendering?</li>
<li>How does @defer compare to lazy loading?</li>
<li>What can be loaded using @defer?</li>
<li>How does @defer compare to @if?</li>
<li>Summary</li>
</ul>
<p><strong>Note</strong>: If you are looking to learn about what else was introduced in Angular 17 together with <code>@defer</code>, check out the following posts:</p>
<ul>
<li><a href="https://blog.angular-university.io/angular-if/">Angular @if: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-for/">Angular @for: Complete Guide</a></li>
<li><a href="https://blog.angular-university.io/angular-switch/">Angular @switch: Complete Guide</a></li>
</ul>
<p>Read more on <code>@defer</code> in the official docs: <a href="https://angular.dev/guide/defer" target="_blank" rel="noopener">Angular @defer</a>.</p>
<h2 id="what-is-defer-and-why-do-we-need-it">What is <code>@defer</code>, and why do we need it?</h2>
<p><code>@defer</code> is an Angular template syntax, that allows you to load parts of a template only when they are needed, given a logical condition.</p>
<p>The <code>@defer</code> syntax allows us to implement common use cases such as:</p>
<ul>
<li>only load a large component after the user scrolls down the page after a certain point</li>
<li>only load a large component after the user clicks on a button</li>
<li>preload a large component on the background while the user is reading the page, so that it is ready by the time the user clicks on a button</li>
</ul>
<p>And these are just a few common examples of what we can do with <code>@defer</code>.</p>
<p>The <code>@defer</code> syntax gives us two levels of control over the process of loading partial resources:</p>
<ul>
<li>
<p>we can control <em>when the code gets fetched</em> from the backend, and this is called <strong>prefetching</strong>.</p>
</li>
<li>
<p>we can also control separately <em>when that code is applied</em> to the page</p>
</li>
</ul>
<p>It's important to understand that these two steps are <strong>not</strong> the same thing.</p>
<p>You might want to load some code on the background anticipating that it will be needed soon, but you don't have to display that code immediately after it gets loaded.</p>
<p>You might want to wait for a certain event to happen, like the user clicking on a button, before you display the code.</p>
<p>With <code>@defer</code> we can define triggers for each of these two steps separately.</p>
<p>We can use predefined triggers, but we can also define our custom triggers if needed.</p>
<p>So we have full flexibility over the whole process of loading and applying the code.</p>
<p>In general, the predefined triggers will be more than enough for most use cases.</p>
<p>Let's then see <code>@defer</code> in action!</p>
<h2 id="defer-in-action"><code>@defer</code> in action</h2>
<p>Imagine that your component has some code that will always be displayed, but then there is a section of the page that is only needed in certain scenarios.</p>
<p>That non-essential section contains a large component, that we want to load on the background.</p>
<p>Here is a simple example of that component:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"large-component"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> &lt;h2>large-component is displayed...&lt;/h2> </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>Just imagine that this is a massive component, that internally uses chart libraries and other heavy dependencies.</p>
<p>We want to delay the loading of this large component until we are 100% sure that the user needs it.</p>
<p>To control when that large component gets loaded in our application, start by wrapping it in a <code>@defer</code> block:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;h2>Some content that will always be displayed ...&lt;/h2>

    @defer {
    &lt;large-component />
    }
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>This will tell Angular that the <code>@defer</code> section of the page should be packaged into a separate Javascript bundle, and loaded separately.</p>
<p>You can see the immediate effect of the presence of the <code>@defer</code> block in the Angular CLI build output:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/angular-defer/01_angular-cli-defer-build-output.jpg" alt="Angular CLI build output where the extra bundle created by @defer is visible" loading="lazy" decoding="async"></p>
<p>As you can see, the use of <code>@defer</code> has created an extra bundle, that contains the code for the <code>large-component</code> element.</p>
<p>This means that <code>large-component</code> and all its dependencies have been extracted from the main application bundle, and are now part of a separate bundle.</p>
<p>So the main application bundle now is smaller, and it should load faster!</p>
<p>The new extra bundle with <code>large-component</code> will be loaded only when the <code>@defer</code> block gets triggered.</p>
<p>Notice that we didn't specify any trigger for the <code>@defer</code> block, so it will be triggered by default when the browser is idle.</p>
<p>The browser is considered idle when all the resources of the page have finished loading, and the browser loading spinner has stopped.</p>
<p>This means that the <code>large-component</code> bundle will be loaded and displayed very soon after the AppComponent is fully rendered.</p>
<p>To make it clearer, this is what is happening at this point:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/angular-defer/02-initial-use-of-defer-v2.jpg" alt="a bundle getting loaded with @defer" loading="lazy" decoding="async"></p>
<p>As we can see, the following is happening:</p>
<ul>
<li>the main application bundle is loaded first</li>
<li>then the <code>@defer</code> bundle is loaded, containing the <code>large-component</code> and all its dependencies</li>
<li>we can see the extra bundle being loaded last in the network tab, at the bottom right</li>
<li>then the <code>large-component</code> is rendered, as we can see on the top right</li>
</ul>
<p>So this establishes the fundamentals of how <code>@defer</code> works under the hood.</p>
<p>But now the question is, how can we better control the behavior of <code>@defer</code>:</p>
<ul>
<li>how can we control when the bundle gets loaded?</li>
<li>how can we control when the <code>large-component</code> gets rendered?</li>
<li>can we display a loading indicator while the bundle gets loaded?</li>
<li>can we display an error message if the bundle fails to load?</li>
<li>can we display some initial content that will be displayed before the bundle gets loaded?</li>
</ul>
<p>We are going to answer all these questions next!</p>
<p>But to answer many of these questions, we need to first introduce the companion blocks of <code>@defer</code>: the <code>@placeholder</code>, <code>@loading</code>, and <code>@error</code> blocks.</p>
<h2 id="defer-with-placeholder"><code>@defer</code> with <code>@placeholder</code></h2>
<p>Sometimes we just want to display a blank space in the place where our<br>
<code>@defer</code> block is placed.</p>
<p>But other times, we want to display some initial content to the user, that will later be replaced by the code loaded via the <code>@defer</code> block.</p>
<p>We can do that by wrapping the initial content that we want to display in a <code>@placeholder</code> block:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} 
@placeholder {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>initial-content</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>So here is how this works:</p>
<ul>
<li>
<p>Initially, the <code>&lt;initial-content /&gt;</code> component is rendered, in the place where the <code>@defer</code> block is placed inside the page.</p>
</li>
<li>
<p>When the <code>@defer</code> block gets loaded and rendered, only then will the <code>&lt;initial-content /&gt;</code> be replaced with <code>&lt;large-component /&gt;</code>.</p>
</li>
</ul>
<p><strong>Note</strong>: Any components, directives, pipes, etc. used inside the <code>@placeholder</code> will be eagerly loaded, and will be part of the main bundle.</p>
<p>So do <strong>not</strong> use heavy dependencies that you want to be deffer loaded inside the <code>@placeholder</code> block.</p>
<p>The placeholder component should typically be something very simple and lightweight.</p>
<p>It's just a visual indicator that something will be placed in that space soon.</p>
<h2 id="placeholder-parameters"><code>@placeholder</code> parameters</h2>
<p>The <code>@placeholder</code> block can take one optional parameter called <code>minimum</code>, which is a time duration in seconds or milliseconds.</p>
<p><code>minimum</code> is used to set the minimum amount of time for which the placeholder block will be shown to the user:</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} 
@placeholder (minimum 2s) {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>initial-content</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>The above code will render the <code>&lt;initial-content /&gt;</code> for 2 seconds before the <code>&lt;large-component /&gt;</code> appears.</p>
<p>This minimum display time is useful to help prevent bad UI user experience.</p>
<p>This is because depending on the network speed, the <code>@defer</code> block might show the placeholder just for a split second.</p>
<p>In that case, the user would just see some weird flickering effect on the page, which could give the feeling that something is broken, when it's not the case.</p>
<p>The <code>minimum</code> parameter helps with that, as it makes sure that the placeholder is displayed long enough for the user to see it and understand what it is, before it disappears.</p>
<h2 id="defer-with-loading"><code>@defer</code> with <code>@loading</code></h2>
<p>The <code>@loading</code> block is used to show some content while the <code>@defer</code> block is <strong>still loading</strong> its Javascript bundle in the background.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} 
@loading {
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-spinner</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>The <code>&lt;loading-spinner /&gt;</code> will be rendered only while the <code>&lt;large-component /&gt;</code> bundle loads. When the loading is completed, the <code>&lt;loading-spinner /&gt;</code> will be removed from the page, and the <code>&lt;large-component /&gt;</code> will be rendered in its place.</p>
<p>Notice that any dependencies inside the <code>@loading</code> block are all eagerly loaded as well, just like in the case of <code>@placeholder</code>.</p>
<p>The <code>@loading</code> block accepts two optional parameters:<code>minimum</code> and <code>after</code>:</p>
<ul>
<li>
<p><code>minimum</code> is used to specify the minimum amount of time that the <code>@loading</code> block will be shown to the user.</p>
</li>
<li>
<p><code>after</code> is used to specify the amount of time we should wait before showing the <code>@loading</code> indicator after the loading process is started.</p>
</li>
</ul>
<p>Both parameters can be expressed in seconds or milliseconds, and they both are meant to help unwanted flickering effects in the user interface.</p>
<p>Here is an example of how these parameters can be combined:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @loading (after 1s; minimum 2s) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-spinner</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<ul>
<li>
<p>The <code>@loading</code> block above will wait for 1 second after the loading begins before displaying its block contents.</p>
</li>
<li>
<p>The <code>@loading</code> block contents will be displayed for 2 secs before the <code>&lt;large-component /&gt;</code> is rendered.</p>
</li>
</ul>
<p>Notice that if the loading takes less than the <code>after</code> value of 1 second, then the <code>@loading</code> element will never be displayed.</p>
<p>This means that:</p>
<ul>
<li>
<p>the loading indicator will only be shown if the loading takes more than 1 second, otherwise, it will never be displayed</p>
</li>
<li>
<p>if the loading indicator ever gets shown and then the loading completes, we don't want it to be hidden from the user too quickly.</p>
</li>
<li>
<p>so we set a minimum display time of 2 seconds. This means that <em>if</em> the loading indicator ever gets shown at all, it will be displayed for at least 2 seconds.</p>
</li>
</ul>
<p>This prevents the indicator from disappearing too quickly, which could give the impression that something is broken.</p>
<h1 id="the-difference-between-placeholder-and-loading">The difference between <code>@placeholder</code> and <code>@loading</code></h1>
<p>The two blocks seem similar, but they serve different purposes.</p>
<p>The <code>@placeholder</code> is displayed initially until the contents of the <code>@defer</code> block are ready to be rendered.</p>
<p>This block is displayed <em>even before</em> the bundle loading starts. Remember, maybe the loading is triggered only after the user clicks on a button.</p>
<p>So until the bundle loading gets triggered, we might want to display some content to the user and that is where <code>@placeholder</code> comes in.</p>
<p>The <code>@loading</code> block on the other hand only displays when the loading of the bundle of the <code>@defer</code> block has started, and <em>is still ongoing</em>.</p>
<p>After the loading is completed, it disappears.</p>
<h2 id="defer-with-error"><code>@defer</code> with <code>@error</code></h2>
<p>But what if something goes wrong while the bundle is loading, like a network error?</p>
<p>The <code>@error</code> block is used to display content when the loading of the <code>@defer</code> block fails for some reason.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @error {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>error-message</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>So now that we are familiar with the multiple defer blocks, let's talk about triggers.</p>
<h2 id="how-do-defer-triggers-work">How do <code>@defer</code> triggers work?</h2>
<p><code>@defer</code> has two levels of control, each with its trigger:</p>
<ul>
<li>
<p>the optional prefetch trigger, which controls when the bundle gets loaded from the backend</p>
</li>
<li>
<p>the optional <code>@defer</code> trigger, which controls when the <code>@defer</code> block gets displayed to the user</p>
</li>
</ul>
<p>Remember, those are two very different events, and we can control them separately and support all sorts of advanced use cases.</p>
<p>When it comes to choosing the right trigger, we have two options available:</p>
<ul>
<li>
<p>we can use predefined triggers, that cover all the most common use cases</p>
</li>
<li>
<p>but we can also define our custom triggers, if necessary</p>
</li>
</ul>
<p>The keyword <code>on</code> is used for predefined triggers, while the keyword <code>when</code> is used for custom triggers.</p>
<p>Let's start with the predefined triggers, here is the complete list:</p>
<ul>
<li>idle</li>
<li>viewport</li>
<li>interaction</li>
<li>hover</li>
<li>immediate</li>
<li>timer</li>
</ul>
<p>These predefined triggers can all be applied both as prefetch triggers or as <code>@defer</code> display triggers.</p>
<p>Let's go through them one by one.</p>
<h2 id="the-idle-built-in-trigger">The idle built-in trigger</h2>
<p>This is the default trigger for <code>@defer</code>, both for prefetching and for displaying the <code>@defer</code> block.</p>
<p>So let's say that we use <code>@defer</code> without any trigger:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>This is equivalent to:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on idle; prefetch on idle) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>Notice that we are using the <code>on</code> keyword and not <code>when</code>, because this is a predefined trigger.</p>
<p>As you can see, <code>idle</code> is both the default prefetch trigger and the default display trigger.</p>
<p>So how does it work?</p>
<p><code>idle</code> triggers when the browser enters the idle state.</p>
<p>This idle state occurs when the browser is done with loading all page resources and is not busy with any other task.</p>
<p>Angular detects this by using the standard <code>requestIdleCallback</code> browser API.</p>
<p>When will this happen? For most applications, the browser will be idle immediately after the page is loaded when the browser loading spinner stops running.</p>
<p>As <code>@defer</code> is part of a component template, this means that <code>idle</code> will usually get triggered in most cases immediately after the component is rendered for the first time.</p>
<h2 id="the-viewport-built-in-trigger-with-placeholder">The viewport built-in trigger with <code>@placeholder</code></h2>
<p>A very common use case for <code>@defer</code> is to want to load a component only when (and if) it becomes visible on the browser's viewport, after scrolling down a long page.</p>
<p>With this strategy, the page will render first the content above the fold, which is immediately visible to the user once the page is loaded.</p>
<p>The rest of the content will be loaded only when and if the user scrolls down the page.</p>
<p>This way, the initial page will load faster, and we avoid loading code that the user might never see.</p>
<p>To support this use case, we have available the <code>viewport</code> trigger:</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on viewport) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @placeholder {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-spinner</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>In this case, the viewport event will be triggered when the <code>@placeholder</code> block becomes visible in the browser viewport.</p>
<p>For this to work, the <code>@placeholder</code> block must contain only a single node.</p>
<h2 id="the-viewport-built-in-trigger-without-placeholder">The viewport built-in trigger without <code>@placeholder</code></h2>
<p>If we don't have a placeholder available, we can still specify an element that triggers the <code>viewport</code> event when it comes into view.</p>
<p>This is done using a template variables:</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

@defer (on viewport(title)) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>This way, the trigger will fire when the <code>#title</code> element becomes visible in the viewport.</p>
<h2 id="the-interaction-built-in-trigger-with-placeholder">The interaction built-in trigger with <code>@placeholder</code></h2>
<p>This trigger is fired when the user directly interacts with an element of the page.</p>
<p>The interaction happens either when the user clicks on the target element, or when it types something in it, in case the element is an input.</p>
<p>An interaction is detected using <code>click</code> or <code>keydown</code> events.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on interaction) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @placeholder {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>placeholder-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>In this case, the interaction events are detected in the <code>&lt;placeholder-component /&gt;</code>.</p>
<h2 id="the-interaction-built-in-trigger-without-placeholder">The interaction built-in trigger without <code>@placeholder</code></h2>
<p>Just like with <code>viewport</code>, we can specify an alternative element in the page that will trigger the <code>interaction</code> event.</p>
<p>This is done using a template variable.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

@defer (on interaction(title)) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>The <code>@defer</code> block will be triggered only when the <code>#title</code> element is interacted with.</p>
<p>As <code>#title</code> is a div and not an input, this means that the <code>click</code> event will be used to detect the interaction.</p>
<h2 id="the-hover-built-in-trigger-with-placeholder">The hover built-in trigger with<code>@placeholder</code></h2>
<p>This trigger is fired when the user hovers over an element of the page. The hover events are <code>mouseenter</code> and <code>focusin</code>.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on hover) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @placeholder {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>loading-spinner</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>These events are triggered on the <code>@placeholder</code> block, provided that it contains only a single node.</p>
<h2 id="the-hover-built-in-trigger-without-placeholder">The hover built-in trigger without<code>@placeholder</code></h2>
<p>We can also specify an element that will trigger the <code>@hover</code> event when it is hovered over. This is done using template variables.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">#title</span><span class="token punctuation">></span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>

@defer (on hover(title)) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>The <code>@defer</code> block will be triggered when the <code>#title</code> is hovered over or focused.</p>
<h2 id="the-immediate-built-in-trigger">The immediate built-in trigger</h2>
<p>This triggers the <code>@defer</code> block immediately. It does not wait for any event to be fired.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on immediate) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>This means that we won't even wait for the browser to be idle to trigger this event.</p>
<h2 id="the-timer-built-in-trigger">The timer built-in trigger</h2>
<p>This trigger is fired when a timer duration is reached.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on timer(5s)) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>The <code>@defer</code> block will be triggered after 5 seconds.</p>
<p>The value of the timer can be in milliseconds (ms) or seconds (s).</p>
<p>And with this, we have covered all the built-in triggers!</p>
<p>Let's now talk about pre-fetching.</p>
<h2 id="prefetching-defer-blocks">Prefetching <code>@defer</code> blocks</h2>
<p>Prefetching is the process of loading resources and keeping them in memory before they are needed.</p>
<p>In the previous sections, we demonstrated on each built-in trigger works.</p>
<p>But remember, when using <code>@defer</code> we have two levels of control:</p>
<ul>
<li>we can control when the bundle gets pre-fetched from the backend</li>
<li>we can also control when the <code>@defer</code> block gets displayed to the user</li>
</ul>
<p>So far we have only been configuring the display trigger while leaving the prefetch trigger in its default state.</p>
<p>So this configuration:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on timer(5s)) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>Is functionally equivalent to:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on timer(5s); prefetch on idle) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>As you can see, the bundle is getting pre-fetched when the browser becomes idle, which is the default behavior.</p>
<p>But then the <code>&lt;large-component /&gt;</code> is only shown to the user after 5 seconds, even if the pre-fetching has finished long before that.</p>
<p>The <code>idle</code> trigger is a great default for prefetching, but we can also use any of the other built-in triggers that we have learned, as well as define our custom triggers.</p>
<p>Let's see a couple of examples of what we can do with the prefetch option.</p>
<h2 id="prefetching-on-the-viewport-displaying-on-interaction">Prefetching on the viewport, displaying on interaction</h2>
<p>Imagine that you have a large component below the fold, so you want to start loading it only when the user scrolls down the page.</p>
<p>Then you want to display it only when the user types in something on an input box.</p>
<p>You can do that in the following way:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on interaction; prefetch on viewport) {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
} @placeholder {
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token punctuation">/></span></span>
}
</code></pre></div>
<p>As you can see, all the built-in triggers can be used both for prefetching and for displaying the <code>@defer</code> block.</p>
<p>We can combine them to support all sorts of advanced use cases.</p>
<p>But what if the existing built-in triggers don't do exactly what we need?</p>
<h2 id="custom-defer-triggers-with-the-when-keyword">Custom <code>@defer</code> triggers with the <code>when</code> keyword</h2>
<p>If we need to, we can define our custom triggers using the <code>when</code> keyword.</p>
<p>Here is an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  selector<span class="token operator">:</span> <span class="token string">"app"</span><span class="token punctuation">,</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;button (click)="onLoad()">Trigger Prefetch&lt;/button>

    &lt;button (click)="onDisplay()">Trigger Display&lt;/button>

    @defer(when show; prefetch when load) {
    &lt;large-component />
    }
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
  load<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  show<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

  <span class="token function">onLoad</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>load <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">onDisplay</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>show <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In this example, both the prefetch and the display events are configured using custom triggers.</p>
<p>This gives us full flexibility to implement any custom edge cases that we might run into.</p>
<p>Here is how this works:</p>
<ul>
<li>
<p>click on the Preload button, and the loading of the <code>@defer</code> Javascript bundle will be triggered in the background</p>
</li>
<li>
<p>However, the <code>@defer</code> block will not be displayed yet, because the <code>show</code> variable is still false</p>
</li>
<li>
<p>Then click on the Display button, and the <code>@defer</code> block will be displayed, long after the bundle has finished loading</p>
</li>
<li>
<p>On the other hand, refresh the page, and this time click on the Display button first.</p>
</li>
<li>
<p>You will notice that this will trigger the prefetching as well, and then the block gets immediately displayed.</p>
</li>
</ul>
<p>This means that we can configure a custom prefetch trigger, but if the display trigger gets fired first, the pre-fetching will be done instantly and the prefetch condition will be bypassed.</p>
<p>This makes sense because we can't display the <code>@defer</code> block without the bundle being loaded first.</p>
<h2 id="what-happens-when-defer-is-used-with-server-side-rendering">What happens when <code>@defer</code> is used with server-side rendering?</h2>
<p>When an application is rendered on the server, all the typical browser events are not available in that context.</p>
<p>This means the idle event is not available, nor is the timer event, and the viewport event does not make sense on the server as there is no notion of scrolling, etc.</p>
<p>This means that most of the <code>@defer</code> triggers do not make sense in a server context, so they are all ignored.</p>
<p>So, how can the server handle <code>@defer</code> blocks then?</p>
<p>The server doesn't want to eagerly load the content of the <code>@defer</code> block and render it either, because that defeats the whole purpose of the <code>@defer</code> feature.</p>
<p>The only thing that the server can do when it comes to <code>@defer</code> is to do the initial render of the <code>@placeholder</code> block, if it exists.</p>
<p>Then on the front end, the deferred loading will take place as usual, after the application startup.</p>
<h2 id="how-does-defer-compare-to-lazy-loading">How does <code>@defer</code> compare to lazy loading?</h2>
<p>Imagine an application with 20 different screens, but for typical user sessions, only 2 or 3 are usually needed.</p>
<p>Why load all 20 screens at once then?</p>
<p>That delays the startup of the application and makes it feel slower.</p>
<p>Worse, as the application grows, the number of screens and components grows as well, and the application startup time will keep increasing over time.</p>
<p>To help with that, Angular provides us with lazy loading of components, based on routing configuration.</p>
<p>So if a user navigates to a certain browser path, only then the code for that screen will be loaded.</p>
<p>This already helps a lot in reducing the size of our main application bundle, by splitting it up into screen-level bundles that contain all the code for a given screen.</p>
<p>This router-based mechanism is known as lazy loading.</p>
<p>But what if you want to load only parts of a screen or only parts of a component?</p>
<p>Imagine that one of your screens has a ton of components, that are only visible if the user scrolls down the page, or when the user types in a search bar and clicks enter.</p>
<p>Why load the code for all those components initially, if the user might not even need them?</p>
<p>That is where <code>@defer</code> comes in.</p>
<p>The <code>@defer</code> syntax allows you to load parts of a template only when necessary, given a logical condition.</p>
<p>This deferred loading can be triggered by a variety of events, like the user scrolling down the page, or the user clicking on a button.</p>
<p>The <code>@defer</code> mechanism is not linked to the router, unlike lazy loading, and it's much more fine-grained, we have a lot more control over it.</p>
<p>The <code>@defer</code> feature does not replace lazy loading, it complements it.</p>
<p>The two features are designed to be used together.</p>
<h2 id="what-can-be-loaded-using-defer">What can be loaded using <code>@defer</code>?</h2>
<p>We can only use <code>@defer</code> to load standalone components and their dependencies: components, directives, pipes, CSS, etc.</p>
<p>So one more good reason to migrate our applications to standalone components, using the automated migration available via the Angular CLI.</p>
<h2 id="how-does-defer-compare-to-if">How does <code>@defer</code> compare to <code>@if</code>?</h2>
<p>The two serve two completely different purposes. <code>@defer</code> is not a replacement or an alternative to <code>@if</code>.</p>
<p>It's true that <code>@defer</code> will also initially hide a block given a logical condition just like <code>@if</code>, but that is where the similarities end.</p>
<p>With <code>@defer</code>, once the logical condition gets triggered and the component gets loaded and displayed, there is no turning back.</p>
<p>There is no way to hide the component again if needed using <code>@defer</code>, that can only be done with <code>@if</code>.</p>
<p>So if you need to conditionally show or hide a component that you don't want to load initially, combine the two:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@defer (on interaction; prefetch on viewport) { 
  @if (someCondition) {
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>large-component</span> <span class="token punctuation">/></span></span>
  } 
  @placeholder {
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>placeholder-component</span> <span class="token punctuation">/></span></span>
  }
}
</code></pre></div>
<p>With this setup, the <code>&lt;large-component /&gt;</code> will only be loaded when the user scrolls down the page.</p>
<p>The <code>@defer</code> block will then be applied to the page, but that does not mean that the <code>&lt;large-component /&gt;</code> is visible yet.</p>
<p>The <code>&lt;large-component /&gt;</code> will only be displayed if <code>someCondition</code> is true, if the condition is false, it will remain hidden.</p>
<p>The bottom line is that <code>@defer</code> is meant to control when the code gets loaded and applied to the component, and <code>@if</code> is meant to control the component visibility.</p>
<p>I hope that you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>@defer</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>I hope you enjoyed this deep dive into the Angular <code>@defer</code> template syntax.</p>
<p>As you can see, <code>@defer</code> is a powerful performance optimization tool that is complementary to lazy loading.</p>
<p>The two are meant to be used together, one does not replace the other.</p>
<p>The key thing to understand about <code>@defer</code> is that it gives us two separate levels of control, that we can configure separately:</p>
<ul>
<li>
<p>we can control when the deferred Javascript bundle gets loaded with the <code>prefetch</code> trigger</p>
</li>
<li>
<p>once the bundle is loaded, we can then control when the deferred block gets applied to the page</p>
</li>
</ul>
<p>To control both of these steps, we have a variety of predefined triggers available, and we can also even define our custom triggers if we need to.</p>
<p>In general, the predefined triggers should be more than enough for most use cases.</p>
<p>But if we really need to, we have full flexibility for creating our own custom triggers.</p>
<p>So, what do you think about the new <code>@defer</code> syntax?</p>
<p>Let me know in the comments below how you are planning on using it.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @switch: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-switch/</link>
      <guid isPermaLink="false">65578a8645fab40001ae6ed3</guid>
      <pubDate>Mon, 20 Nov 2023 09:02:17 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to the new Angular @switch template syntax.</description>
      <content:encoded><![CDATA[<p>Angular 17 introduced a new template syntax called <code>@switch</code>, that allows to show or hide template sections depending on a logical condition.</p>
<p>This new syntax is an alternative to the previous <code>ngSwitch</code> structural directive.</p>
<p>In this guide, I will explain the <code>@switch</code> template syntax and how to use it in your Angular application.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post covers the following topics:</p>
<ul>
<li>What is <code>@switch</code>?</li>
<li>Using <code>@switch</code> with multiple <code>@case</code> blocks</li>
<li>The <code>@default</code> clause in <code>@switch</code></li>
<li><code>ngSwitch</code> vs <code>@switch</code></li>
<li>Migrating to <code>@switch</code> using the Angular CLI</li>
<li>Summary</li>
</ul>
<p><strong>Note</strong>: If you're looking for the <code>@if</code> or <code>@for</code> syntaxes, check out my other guides:</p>
<ul>
<li>
<p><a href="https://blog.angular-university.io/angular-if/">Angular @if: Complete Guide</a></p>
</li>
<li>
<p><a href="https://blog.angular-university.io/angular-for/">Angular @for: Complete Guide</a></p>
</li>
</ul>
<p>You can read all about <code>@switch</code> and the new template syntax in the official docs: <a href="https://angular.dev/guide/templates/control-flow" target="_blank" rel="noopener">Angular Control Flow</a>.</p>
<h2 id="what-is-switch">What is <code>@switch</code>?</h2>
<p>The <code>@switch</code> syntax is for Angular what the <code>switch</code> statement is for Javascript.</p>
<p>The <code>@switch</code> template syntax is used to select the right template section to render based on the value of an expression.</p>
<p>Typically you want to use <code>@switch</code> when you have at least 2 or more different options to display, depending on the value of the expression.</p>
<p>If on the other hand you only have two options to display, you usually want to use the <code>@if</code> syntax instead.</p>
<p>Notice that the <code>@switch</code> template syntax is <strong>not</strong> a directive. This feature is built right into the template engine, just like <code>@if</code> or <code>@for</code>.</p>
<p>Here is how it works.</p>
<h2 id="using-switch-with-multiple-case-blocks">Using <code>@switch</code> with multiple <code>@case</code> blocks</h2>
<p>Let's see an example of <code>@switch</code> in action:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">@<span class="token keyword">switch</span> <span class="token punctuation">(</span>color<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    @<span class="token keyword">case</span> <span class="token punctuation">(</span><span class="token string">"red"</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">&lt;</span>div<span class="token operator">></span>Red<span class="token operator">&lt;</span><span class="token operator">/</span>div<span class="token operator">></span>
    <span class="token punctuation">}</span>
    @<span class="token keyword">case</span> <span class="token punctuation">(</span><span class="token string">"blue"</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">&lt;</span>div<span class="token operator">></span>Blue<span class="token operator">&lt;</span><span class="token operator">/</span>div<span class="token operator">></span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The code above will render:</p>
<ul>
<li>&quot;Red&quot; if the value of the <code>color</code> variable is &quot;red&quot;</li>
<li>&quot;Blue&quot; if the value of the <code>color</code> variable is &quot;blue&quot;</li>
</ul>
<p>You can see the similarities between <code>@switch</code> and the Javascript switch statement:</p>
<div class="code-block"><span class="code-lang">js</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-javascript"><code class="language-javascript"><span class="token keyword">switch</span> <span class="token punctuation">(</span>color<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">case</span> <span class="token string">"red"</span><span class="token operator">:</span>
    <span class="token comment">// code</span>
    <span class="token keyword">break</span><span class="token punctuation">;</span>
  <span class="token keyword">case</span> <span class="token string">"blue"</span><span class="token operator">:</span>
    <span class="token comment">// code</span>
    <span class="token keyword">break</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<h2 id="the-default-clause-in-switch">The <code>@default</code> clause in <code>@switch</code></h2>
<p>The <code>@default</code> clause is used to render a template when none of the <code>@case</code> blocks matches the value of the expression.</p>
<p>Let's see an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string"> @switch (color) { 
  @case ("red") {
      &lt;div>Red&lt;/div>
    } 
    @case ("blue") {
      &lt;div>Blue&lt;/div>
    } 
    @default {
      &lt;div>Default&lt;/div>
    } }</span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">AppComponent</span> <span class="token punctuation">{</span>
  color <span class="token operator">=</span> <span class="token string">"green"</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The code above will render &quot;Default&quot; because none of the <code>@case</code> blocks matches the value &quot;green&quot; of the color variable.</p>
<h2 id="ngswitch-vs-switch"><code>ngSwitch</code> vs <code>@switch</code></h2>
<p>The <code>@switch</code> syntax is a direct replacement for the <code>ngSwitch</code> structural directive.</p>
<p>It has the following benefits over the <code>ngSwitch</code> directive:</p>
<ul>
<li>
<p>it's much more intuitive, it reads just like a plain switch statement in Javascript</p>
</li>
<li>
<p>no explicit imports are needed in standalone components. The <code>@switch</code> syntax is automatically available in all templates, unlike <code>ngSwitch</code></p>
</li>
</ul>
<h2 id="migrating-to-switch-using-the-angular-cli">Migrating to <code>@switch</code> using the Angular CLI</h2>
<p>The Angular CLI has a command that can be used to migrate from <code>ngSwitch</code> to <code>@switch</code>:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng generate @angular/core:control-flow
</code></pre></div>
<p>This command will migrate all the <code>*ngSwitch</code> directives in your project to the new syntax, and it will do the same for <code>@if</code> and <code>@for</code>.</p>
<p>I hope you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular Core like <code>@switch</code>, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we explored the new <code>@switch</code> template syntax in detail.</p>
<p>As you can see, it's super intuitive and it reads just like a plain switch statement in Javascript.</p>
<p>No imports are needed, and you can easily migrate to it using the Angular CLI.</p>
<p>So go ahead and try it out, and let me know in the comments below of any questions you might have!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @for: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-for/</link>
      <guid isPermaLink="false">655600ec45fab40001ae6e68</guid>
      <pubDate>Thu, 16 Nov 2023 14:30:42 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to all the features and best practices of the new @for template syntax, as well as a full explanation of the now mandatory tracking function.</description>
      <content:encoded><![CDATA[<p>With the release of Angular 17, a much better developer experience is available with the new control flow syntax, which includes the <code>@for</code> syntax.</p>
<p>Previously, we were required to import the <code>ngFor</code> directive from<br>
<code>@angular/common</code> to iterate over arrays in Angular templates.</p>
<p>But now, the <code>@for</code> built-in template syntax simplifies template iteration, offering a looping mechanism that is much more intuitive to developers.</p>
<p>The <code>@for</code> syntax is a better alternative to <code>@if</code>, <strong>offering a more concise and performance-safe experience compared to <code>ngFor</code></strong>, without requiring any additional imports.</p>
<p>In this guide, we will dive into all the features available with the <code>@for</code> syntax, and compare it to the conventional <code>ngFor</code>.</p>
<p>Let's dive right in!</p>
<h2 id="table-of-contents">Table of Contents</h2>
<ul>
<li>Introducing the new @for syntax</li>
<li>Breaking down @for step by step</li>
<li>What is the @for tracking function?</li>
<li>What if there is nothing unique about the looped element?</li>
<li>Why is the tracking function now mandatory in @for?</li>
<li>How to solve the &quot;NG5002: @for loop must have a &quot;track&quot; expression&quot; error</li>
<li>@for with @empty</li>
<li>@for with String</li>
<li>@for with Iterable objects</li>
<li>@for with $index</li>
<li>@for with $first and $last</li>
<li>@for with $odd and $even</li>
<li>@for with $count</li>
<li>@for vs. ngFor: A side-by-side comparison</li>
<li>Migrating to @for using the Angular CLI</li>
<li>Summary</li>
</ul>
<h2 id="related-articles">Related Articles</h2>
<p><strong>Note:</strong> If you are looking for the traditional <code>*ngFor</code> syntax, you can check out my other tutorial here: <a href="https://blog.angular-university.io/angular-2-ngfor/">Angular ngFor: Complete Guide</a></p>
<p>Looking for <code>@if</code> instead? Check out <a href="https://blog.angular-university.io/angular-if/">Angular @if: Complete Guide</a>.</p>
<p>You can read all about <code>@for</code> and the new template syntax in the official docs: <a href="https://angular.dev/guide/templates/control-flow" target="_blank" rel="noopener">Angular Control Flow</a>.</p>
<h2 id="introducing-the-new-for-template-syntax">Introducing the new @for template syntax</h2>
<p>The <code>@for</code> template syntax is to Angular what the traditional <code>for...loop</code> is to JavaScript.</p>
<p>This syntax is built into the Angular template engine itself, so there is no need to import it manually into standalone components, unlike <code>ngFor</code>.</p>
<h2 id="breaking-down-for-step-by-step">Breaking down @for step by step</h2>
<p>Let's take a look at the <code>@for</code> syntax:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">@<span class="token keyword">for</span> <span class="token punctuation">(</span>item <span class="token keyword">of</span> items<span class="token punctuation">;</span> track item<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// template content to repeat</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The <code>@for</code> block is composed of several parts:</p>
<ul>
<li>
<p><code>@for</code> keyword: The <code>@for</code> keyword is the entry point to the <code>@for</code> block. It is followed by a pair of parentheses containing the iteration logic.</p>
</li>
<li>
<p><code>item</code>: The <code>item</code> statement declares a variable that will be used to represent each item in the collection. This variable is scoped to the<br>
<code>@for</code> block, and it's not visible outside of it.</p>
</li>
<li>
<p><code>of items</code>: The <code>of items</code> statement defines the collection to be iterated over. This collection can be an array, a string, or anything that is iterable in general. It doesn't necessarily need to be an array, but that is the most common case.</p>
</li>
<li>
<p><code>track item</code>: The <code>track item</code> statement is used to track the items by reference. This statement is <strong>required</strong>. It is used to optimize performance by preventing unnecessary change detection runs when the data changes. If this statement is not included, you will get a compilation error (more on this later).</p>
</li>
<li>
<p><code>// content to repeat</code>: This is the content to be repeated for each item in the array.</p>
</li>
</ul>
<p>Let's take a look at a simple example of <code>@for</code> in action:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (color of colors; track color) {
    &lt;li>{{ color }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  colors <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Red"</span><span class="token punctuation">,</span> <span class="token string">"Blue"</span><span class="token punctuation">,</span> <span class="token string">"White"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Let's break down this example:</p>
<ul>
<li>
<p>The <code>@for</code> block is used to iterate over the <code>colors</code> array.</p>
</li>
<li>
<p>The <code>color</code> statement declares a variable named <code>color</code> that will be used to represent each item in the <code>colors</code> array.</p>
</li>
<li>
<p>The <code>of colors</code> statement defines the <code>colors</code> array as the collection to be iterated over.</p>
</li>
<li>
<p>The <code>track color</code> statement is used to track the items by reference because each item is a string. We will see an example with objects later.</p>
</li>
</ul>
<p>In the DOM, the <code>@for</code> block is rendered as follows:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Red<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Blue<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>White<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>As you can see, the <code>@for</code> example is very similar to the JavaScript's <code>for..of</code> loop, almost identical:</p>
<div class="code-block"><span class="code-lang">js</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-javascript"><code class="language-javascript"><span class="token keyword">const</span> colors <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Red"</span><span class="token punctuation">,</span> <span class="token string">"Blue"</span><span class="token punctuation">,</span> <span class="token string">"White"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> color <span class="token keyword">of</span> colors<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>color<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>This is intentional, as the <code>@for</code> syntax is designed to be very familiar and intuitive to JavaScript developers.</p>
<p>Here is a video from <a href="https://www.youtube.com/@AngularUniversity" target="_blank" rel="noopener">our YouTube channel</a> demonstrating the new <code>@for</code> syntax in action:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/Aq4u8sjxRlA?si=2ZIPNavVoLF_UKjD" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<p>The most noticeable change when compared to the previous <code>ngFor</code> structural directive is that now the tracking function is mandatory, unlike before.</p>
<h2 id="what-is-the-for-tracking-function">What is the @for tracking function?</h2>
<p>The tracking function created via the <code>track</code> statement is used to make it easy for the Angular change detection mechanism to know exactly what items to update in the DOM after the input array changes.</p>
<p>The tracking function tells Angular how to uniquely identify an element of the list.</p>
<p>For example, if just one element was added to a list of 100, we want Angular to be able to just append that new element to the DOM, without having to re-render all the other elements unnecessarily.</p>
<p>That is just one example of the kind of optimizations that the tracking function enables.</p>
<p>To be effective, the tracking function should identify something unique about the element in the list.</p>
<p>If there isn't anything unique about the element, then the tracking function should return the index of the element in the array (I will show you how to do that later).</p>
<p>Let's see an example of a simple tracking function in a very common scenario - when looping through an array of objects:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (course of courses; track course.id) {
    &lt;li>{{ course }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">CoursesComponent</span> <span class="token punctuation">{</span>
  courses <span class="token operator">=</span> <span class="token punctuation">[</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">2</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">3</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular Forms In Depth"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we are creating a tracking function that uses the <code>id</code> property, which is unique for each course.</p>
<p>Notice also that we are <em>not</em> passing a function in this example to <code>track</code>.</p>
<p>We are instead passing <code>track course.id</code>, which is a shorthand for a function that takes in a course and returns an id.</p>
<p>Angular will take this simplified notation and convert it to a function.</p>
<p>But there are scenarios where the tracking function is not that simple, and we need to write that function ourselves.</p>
<p>Here is an equivalent example to the <code>track course.id</code> shorthand above, but using an actual function:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (course of courses; track trackCourse) {
    &lt;li>{{ course }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">CoursesComponent</span> <span class="token punctuation">{</span>
  courses <span class="token operator">=</span> <span class="token punctuation">[</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular For Beginners"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">2</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular Core Deep Dive"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">{</span> id<span class="token operator">:</span> <span class="token number">3</span><span class="token punctuation">,</span> name<span class="token operator">:</span> <span class="token string">"Angular Forms In Depth"</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">]</span><span class="token punctuation">;</span>

  <span class="token function">trackCourse</span><span class="token punctuation">(</span>index<span class="token operator">:</span> <span class="token builtin">number</span><span class="token punctuation">,</span> course<span class="token operator">:</span> Course<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> course<span class="token punctuation">.</span>id<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we do still keep the full flexibility of writing our own tracking function, if we really need to.</p>
<p>But in most cases, the shorthand notation will be enough.</p>
<h2 id="what-if-there-is-nothing-unique-about-the-looped-element">What if there is nothing unique about the looped element?</h2>
<p>In principle, there should always be something unique about the elements being looped.</p>
<p>For example, in the case of an array of strings you can use the string reference itself because that is guaranteed to be unique:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (course of courses; track course) {
    &lt;li>{{ course }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">CoursesComponent</span> <span class="token punctuation">{</span>
  courses <span class="token operator">=</span> <span class="token punctuation">[</span>
    <span class="token string">"Angular For Beginners"</span><span class="token punctuation">,</span>
    <span class="token string">"Angular Core Deep Dive"</span><span class="token punctuation">,</span>
    <span class="token string">"Angular Forms In Depth"</span><span class="token punctuation">,</span>
  <span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>In the worst-case scenario, if there is nothing unique about the array elements, you can always safely fall back to the <code>$index</code> of the element, meaning the position of the element in the array.</p>
<p>Using <code>$index</code> is not ideal in terms of the optimizations that could be done, but it already helps in certain scenarios.</p>
<p>Later in the <code>$index</code> section, I will show you how to use it to write a tracking function.</p>
<h2 id="why-is-the-tracking-function-now-mandatory-in-for">Why is the tracking function now mandatory in @for?</h2>
<p>The tracking function is essential to prevent developers from shooting themselves in the foot and experiencing unexpected performance slowdowns in their applications.</p>
<p>The tracking function acts like a safety net.</p>
<p>According to <a href="https://medium.com/@mgechev" target="_blank" rel="noopener">Minko Gechev</a> in <a href="https://blog.angular.io/introducing-angular-v17-4d7033312e4b" target="_blank" rel="noopener">the post where @for was introduced</a>:</p>
<blockquote>
<p>We often see performance problems in apps due to the lack of trackBy function in <code>*ngFor</code>. A few differences in <code>@for</code>are that <code>track</code> is mandatory to ensure fast diffing performance. In addition, it’s way easier to use since it’s just an expression rather than a method in the component’s class.</p>
</blockquote>
<p>As the tracking function is now mandatory, the <code>@for</code> syntax is performance-wise much safer to use than the previous <code>ngFor</code>.</p>
<h2 id="how-to-solve-the-ng5002-for-loop-must-have-a-track-expression-error">How to solve the &quot;NG5002: @for loop must have a &quot;track&quot; expression&quot; error</h2>
<p>For reference, this is the error that the compiler will throw at you if you forget to add a tracking function to your <code>@for</code> block.</p>
<p>Simply add a tracking function using the best practices described above, and the error will be fixed.</p>
<h2 id="for-with-empty">@for with @empty</h2>
<p>Now in the following sections, we are going to explore all the nice extra features of the <code>@for</code> syntax.</p>
<p>Let's start with the <code>@empty</code> keyword.</p>
<p>The <code>@empty</code> keyword is used to render content when the collection is empty. This is useful for example for displaying a message to the user when an array is empty.</p>
<p>Here is what the <code>@empty</code> syntax looks like:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">
Example<span class="token operator">:</span>

<span class="token template-string"><span class="token template-punctuation string">`</span><span class="token template-punctuation string">`</span></span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">ts
@Component({
  template: </span><span class="token template-punctuation string">`</span></span><span class="token operator">&lt;</span>ul<span class="token operator">></span>
    @<span class="token keyword">for</span> <span class="token punctuation">(</span>item <span class="token keyword">of</span> items<span class="token punctuation">;</span> track item<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">&lt;</span>li<span class="token operator">></span><span class="token punctuation">{</span><span class="token punctuation">{</span> item <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token operator">&lt;</span><span class="token operator">/</span>li<span class="token operator">></span>
    <span class="token punctuation">}</span>
    <span class="token decorator"><span class="token at operator">@</span><span class="token function">empty</span></span> <span class="token punctuation">{</span>
    <span class="token operator">&lt;</span>li<span class="token operator">></span>No items found<span class="token operator">&lt;</span><span class="token operator">/</span>li<span class="token operator">></span>
    <span class="token punctuation">}</span>
  <span class="token operator">&lt;</span><span class="token operator">/</span>ul<span class="token operator">></span>`<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here, the <code>@for</code> block is used to iterate over the <code>items</code> array. The <code>@empty</code> keyword is used to render the message &quot;No items found&quot; only when the <code>items</code> array is empty.</p>
<p>In the DOM, the <code>@for</code> block is rendered as follows:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>No items found<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>This is another advantage that <code>@for</code> has over the traditional <code>ngFor</code> directive. The <code>ngFor</code> directive does not have built-in support for rendering content when the collection is empty.</p>
<p>To achieve the same result with <code>ngFor</code>, we would have to use the <code>ngIf</code> directive to check if the collection is empty, and then render the message in that case.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;ul>
      &lt;ng-container *ngFor="let item of items">
        &lt;li>{{ item }}&lt;/li>
      &lt;/ng-container>
      &lt;ng-container *ngIf="items.length === 0">
        &lt;li>No items found&lt;/li>
      &lt;/ng-container>
    &lt;/ul>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span><span class="token punctuation">[</span><span class="token operator">...</span><span class="token punctuation">,</span> NgForOf<span class="token punctuation">,</span> NgIf<span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, it took much less code to implement this in <code>@for</code>. It's much more readable and maintainable.</p>
<h2 id="for-with-string">@for with String</h2>
<p>The <code>@for</code> built-in can be used to iterate over strings, as strings are iterable.</p>
<p>This is useful for rendering a string character by character:</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (char of "Angular"; track char) {
    &lt;li>{{ char }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</code></pre></div>
<p>In the DOM, the <code>@for</code> block is rendered as follows:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>A<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>n<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>g<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>u<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>l<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>a<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>r<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<h2 id="for-with-iterable-objects">@for with Iterable objects</h2>
<p>It's worth mentioning that the <code>@for</code> syntax can be used to iterate over any object, not just an array.</p>
<p>Iterable objects are objects that implement the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols" target="_blank" rel="noopener">iteration protocol</a>.</p>
<p>Here is an example of how to iterate over an Iterable object, like a Map with two entries:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (entry of myMap; track entry) {
    &lt;li>{{ entry[0] }}: {{ entry[1] }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  <span class="token comment">//This map has two entries. Each entry has a key and a value.</span>
  myMap <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Map</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
    <span class="token punctuation">[</span><span class="token string">"firstName"</span><span class="token punctuation">,</span> <span class="token string">"Angular"</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token punctuation">[</span><span class="token string">"lastName"</span><span class="token punctuation">,</span> <span class="token string">"Framework"</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  <span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, the variable <code>myMap</code> is a Map and not an array. Its values can be accessed like this:</p>
<div class="code-block"><span class="code-lang">js</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-javascript"><code class="language-javascript">myMap<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"firstName"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 'Angular'</span>
myMap<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">"lastName"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//'Framework'</span>
</code></pre></div>
<p>But even though myMap is not an array, we can still loop through it with <code>@for</code> and access its key/value pairs (the Map entries):</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>firstName: Angular<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>lastName: Framework<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>So as you can see, any data type that is Iterable <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" target="_blank" rel="noopener"><code>for..of</code></a> can be used with <code>@for</code>, not just arrays.</p>
<h2 id="for-with-index">@for with $index</h2>
<p>The <code>$index</code> implicit variable is supported in the <code>@for</code> control-flow.</p>
<blockquote>
<p><code>$index</code> holds the index of the current row in the array during its iteration by <code>@for</code>.</p>
</blockquote>
<p>Note: <code>$index</code> is zero-based, so it starts with 0, 1, 2, etc.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (item of items; track item; let index = $index) {
    &lt;li>{{ index }}: {{ item }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Angular"</span><span class="token punctuation">,</span> <span class="token string">"React"</span><span class="token punctuation">,</span> <span class="token string">"Vue"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Here, the output will be:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>0: Angular<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>1: React<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>2: Vue<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<h2 id="for-with-first-and-last">@for with $first and $last</h2>
<p>The <code>$first</code> and <code>$last</code> implicit variables are also supported in the <code>@for</code> control flow:</p>
<ul>
<li><code>$first</code> holds a boolean value indicating if the current item is the first item in the collection.</li>
<li><code>$last</code> holds a boolean value indicating if the current item is the last in the collection.</li>
</ul>
<p>Example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;ul>
      @for (item of items; track item; let first = $first, last = $last) {
      &lt;li>{{ item }}: {{ first }}: {{ last }}&lt;/li>
      }
    &lt;/ul>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Angular"</span><span class="token punctuation">,</span> <span class="token string">"React"</span><span class="token punctuation">,</span> <span class="token string">"Vue"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The output will be:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Angular: true: false<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>React: false: false<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Vue: false: true<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<h2 id="for-with-odd-and-even">@for with $odd and $even</h2>
<p>The <code>$odd</code> and <code>$even</code> implicit variables are also supported:</p>
<ul>
<li><code>$odd</code> holds a boolean value indicating if the current index is an odd number: 1, 3, 5, 7, 9, etc.</li>
<li><code>$even</code> holds a boolean value indicating if the current index is an even number: 0, 2, 4, 6, 8, etc.</li>
</ul>
<p>This information is useful, for example for conveniently applying CSS classes to odd and even rows in a data table.</p>
<p>Example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;ul>
      @for (item of items; track item; let odd = $odd, even = $even) {
      &lt;li>{{ item }}: {{ odd }}: {{ even }}&lt;/li>
      }
    &lt;/ul>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Angular"</span><span class="token punctuation">,</span> <span class="token string">"React"</span><span class="token punctuation">,</span> <span class="token string">"Vue"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The output will be:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Angular: false: true<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>React: true: false<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Vue: false: true<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<h2 id="for-with-count">@for with $count</h2>
<p>The <code>$count</code> implicit variable is supported in the <code>@for</code> control flow.</p>
<p>It contains the total number of elements of the Iterable that we are looping over:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;ul>
      @for (item of items; track item; let count = $count) {
      &lt;li>{{ item }}: {{ count }}&lt;/li>
      }
    &lt;/ul>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Red"</span><span class="token punctuation">,</span> <span class="token string">"Blue"</span><span class="token punctuation">,</span> <span class="token string">"White"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The output will be:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ul</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Red: 3<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>Blue: 3<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>li</span><span class="token punctuation">></span></span>White: 3<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>li</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ul</span><span class="token punctuation">></span></span>
</code></pre></div>
<p>As you can see, it always prints out 3, which is the length of the array.</p>
<h1 id="for-vs-ngfor-a-side-by-side-comparison">@for vs. ngFor: a side-by-side comparison</h1>
<p>The traditional <code>*ngFor</code> or <code>NgForOf</code> directive has been used for template iteration in Angular since its creation.</p>
<p>However, the <code>@for</code> syntax offers several advantages over <code>ngFor</code>:</p>
<ul>
<li>
<p>Less verbosity: The <code>@for</code> syntax is more concise.</p>
</li>
<li>
<p>The <code>@for</code> now forces developers to use a tracking function</p>
</li>
<li>
<p>The <code>@for</code> syntax is automatically included in templates, no explicit imports are needed.</p>
</li>
<li>
<p>The <code>@for</code> built-in offers improved type inference, enabling TypeScript to more accurately determine types within the iteration block.</p>
</li>
</ul>
<p>Let's take a look at a side-by-side comparison of <code>@for</code> and <code>ngFor</code>:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token comment">// @for</span>
<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;ul>
    @for (item of items; track item) {
    &lt;li>{{ item }}&lt;/li>
    }
  &lt;/ul></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Angular"</span><span class="token punctuation">,</span> <span class="token string">"React"</span><span class="token punctuation">,</span> <span class="token string">"Vue"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token comment">// ngFor</span>
<span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    &lt;ul>
      &lt;ng-container *ngFor="let item of items">
        &lt;li>{{ item }}&lt;/li>
      &lt;/ng-container>
    &lt;/ul>
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
  standalone<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
  imports<span class="token operator">:</span><span class="token punctuation">[</span><span class="token operator">...</span><span class="token punctuation">,</span> NgForOf<span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">ExampleComponent</span> <span class="token punctuation">{</span>
  items <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Angular"</span><span class="token punctuation">,</span> <span class="token string">"React"</span><span class="token punctuation">,</span> <span class="token string">"Vue"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<h2 id="migrating-to-for-using-the-angular-cli">Migrating to @for using the Angular CLI</h2>
<p>Angular made it very easy to migrate to <code>@for</code> from <code>ngFor</code>, thanks to Angular CLI's migration tool.</p>
<p>Just run this command and your project will be migrated to <code>@for</code>:</p>
<div class="code-block"><span class="code-lang">sh</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng generate @angular/core:control-flow
</code></pre></div>
<p>I hope you enjoyed this post, to get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up-to-date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular core like <code>@for</code> and others, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we explored in detail the new <code>@for</code> syntax.</p>
<p>We saw how it can be used to iterate over arrays, strings, and any iterable object.</p>
<p>We also saw how it can be used to render content when an array is empty using <code>@empty</code>.</p>
<p>We also learned how we can use it with the <code>$index</code>, <code>$first</code>, <code>$last</code>, <code>$odd</code>, <code>$even</code>, and <code>$count</code> implicit variables that we are familiar with in the traditional <code>NgFor</code> directive.</p>
<p>The <code>@for</code> syntax is more concise, more readable, and safer to use than <code>ngFor</code>, due to the now mandatory tracking function.</p>
<p>Besides, <code>@for</code> does not require manual imports!</p>
<p>So, what do you think about the new <code>@for</code> syntax? Do you like it? Let me know in the comments below.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular @if: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-if/</link>
      <guid isPermaLink="false">65522b054c9e1e0001150d31</guid>
      <pubDate>Mon, 13 Nov 2023 15:06:26 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>A complete guide to all the features of the @if template syntax, including the most frequently asked questions bout this syntax, as well as an anti-pattern to avoid.</description>
      <content:encoded><![CDATA[<p>One of the most significant enhancements to the Angular framework was the introduction of the new built-in syntax for control flow, originally made available in Angular 17.</p>
<p>This syntax helps with one of the most common tasks that we need to do as developers: show or hide elements on a page depending on a logical condition.</p>
<p>In the past, we used to do that with the traditional structural directive <code>*ngIf</code>.</p>
<p>But now we have a <em>much better alternative to <code>ngIf</code></em>: the new <code>@if</code> syntax, which is part of the new template control flow features.</p>
<p>We will compare the two syntaxes, and explain why the new <code>@if</code> syntax is better and <strong>how to automatically migrate to it</strong>.</p>
<p>In this guide, we'll delve into why the new <code>@if</code> is a game-changer, providing a more intuitive and ergonomic alternative to <code>*ngIf</code>.</p>
<p>We'll also talk about a common anti-pattern that developers often encounter, which has to do with the use of <code>@if</code> in conjunction with the <code>async</code> pipe.</p>
<p>Ready to level up your Angular skills? Let's dive in!</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post covers the following topics:</p>
<ul>
<li>Why a new control flow syntax?</li>
<li>What is Angular <code>@if</code>?</li>
<li>The <code>@if</code> syntax</li>
<li>The <code>@if</code> else syntax</li>
<li>The <code>@if</code> else if else syntax</li>
<li>Why don't we need to import <code>@if</code>?</li>
<li>Why don't we need to use the <code>*</code> syntax anymore?</li>
<li>Why is the new <code>@if</code> syntax better than <code>ngIf</code>?</li>
<li>How to easily migrate to the new <code>@if</code> syntax?</li>
<li>How does <code>@if</code> compare to hiding elements using CSS?</li>
<li>Multiple nested <code>@if</code> async pipe anti-pattern</li>
<li>Summary</li>
</ul>
<p><strong>Note:</strong> if you are looking to learn about the old <code>*ngIf</code> syntax instead, check out my other guide here: <a href="https://blog.angular-university.io/angular-ngif/">Angular *ngIf: Complete Guide</a></p>
<p>And if you are looking for the new <code>@switch</code> which is also used for conditional rendering, check out this guide: <a href="https://blog.angular-university.io/angular-switch/">Angular @switch: Complete Guide</a>.</p>
<h2 id="why-a-new-control-flow-syntax">Why a new control flow syntax?</h2>
<p>According to <a href="https://medium.com/@mgechev" target="_blank" rel="noopener">Minko Gechev</a> in <a href="https://blog.angular.io/introducing-angular-v17-4d7033312e4b" target="_blank" rel="noopener">the post where @if was introduced</a><br>
this new built-in control flow syntax enables:</p>
<ul>
<li>
<p>More ergonomic and much less verbose syntax that is closer to JavaScript, thus more intuitive requiring fewer documentation lookups.</p>
</li>
<li>
<p>Template syntax like <code>@if</code> is automatically available in your templates without any additional imports</p>
</li>
<li>
<p>Better type checking thanks to more optimal type narrowing</p>
</li>
<li>
<p>It’s a concept that primarily exists at build-time, which reduces the runtime footprint, helping you drop your bundle size and improve your Core Web vitals.</p>
</li>
<li>
<p>also, the control flow syntax will make it easier to implement signal-based change detection in the future</p>
</li>
</ul>
<p>You can read all about <code>@if</code> and the new template syntax in the official docs: <a href="https://angular.dev/guide/templates/control-flow" target="_blank" rel="noopener">Angular Control Flow</a>.</p>
<h2 id="what-is-angular-if">What is Angular <code>@if</code>?</h2>
<p><code>@if</code> is to Angular what <code>if</code> is to JavaScript.</p>
<p><code>@if</code> is a new template syntax for conditionally rendering elements in Angular templates. It's a built-in control flow syntax that allows you to conditionally show or hide page elements depending on a logical boolean condition.</p>
<p>Unlike the traditional <code>*ngIf</code> structural directive, you don't need to import <code>@if</code> in standalone components, it's automatically available everywhere.</p>
<p>It's a more concise and readable syntax, that also supports <code>else if</code> and <code>else</code> conditions, unlike the previous <code>*ngIf</code> syntax.</p>
<p>Let's explore this syntax in more detail.</p>
<h2 id="the-if-syntax">The <code>@if</code> syntax</h2>
<p>Here is an initial example of how to use this syntax:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    @if (showHello) {
    &lt;h2>Hello&lt;/h2>
    }
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Test</span> <span class="token punctuation">{</span>
  showHello<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The above code will only render the <code>&lt;h2&gt;Hello&lt;/h2&gt;</code> element if the <code>showHello</code> property is <code>true</code>.</p>
<p>Do you see how this syntax is so similar to JavaScript's <code>if</code> statement?</p>
<div class="code-block"><span class="code-lang">js</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-javascript"><code class="language-javascript"><span class="token keyword">if</span> <span class="token punctuation">(</span>showHello<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">&lt;h2>Hello&lt;/h2></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>It's almost identical!</p>
<h2 id="the-if-else-syntax">The <code>@if</code> else syntax</h2>
<p>The <code>@if</code> syntax also supports <code>else</code> conditions, unlike the previous <code>*ngIf</code> syntax.</p>
<p>Let's see an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    @if (showHello) {
    &lt;h2>Hello&lt;/h2>
    } 
    @else {
    &lt;h2>Goodbye&lt;/h2>
    }
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Test</span> <span class="token punctuation">{</span>
  showHello<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The code above will render:</p>
<ul>
<li>the <code>&lt;h2&gt;Hello&lt;/h2&gt;</code> element if the <code>showHello</code> property is <code>true</code></li>
<li>the <code>&lt;h2&gt;Goodbye&lt;/h2&gt;</code> element if the <code>showHello</code> property is <code>false</code></li>
</ul>
<p>This is visually much more like the <code>if-else</code> syntax in JavaScript.</p>
<h2 id="the-if-else-if-else-syntax">The <code>@if</code> else if else syntax</h2>
<p>Angular is not yet done. They also added support for <code>else if</code> conditions. This is something that was not possible with the previous <code>*ngIf</code> syntax.</p>
<p>Let's see an example:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
    @if (showHello) {
      &lt;h2>Hello&lt;/h2>
    } 
    @else if (showGoodbye) {
      &lt;h2>Goodbye&lt;/h2>
    } 
    @else {
      &lt;h2>See you later&lt;/h2>
    }
  </span><span class="token template-punctuation string">`</span></span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">class</span> <span class="token class-name">Test</span> <span class="token punctuation">{</span>
  showHello<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  showGoodbye<span class="token operator">:</span> <span class="token builtin">boolean</span> <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>The code above will:</p>
<ul>
<li>render the <code>&lt;h2&gt;Hello&lt;/h2&gt;</code> element if the <code>showHello</code> property is <code>true</code></li>
<li>the <code>&lt;h2&gt;Goodbye&lt;/h2&gt;</code> element if the <code>showGoodbye</code> property is <code>true</code> and <code>showHello</code> is <code>false</code></li>
<li>the <code>&lt;h2&gt;See you later&lt;/h2&gt;</code> element if both the <code>showHello</code> and <code>showGoodbye</code> properties are <code>false</code>.</li>
</ul>
<p>Again, this is so close to what we would write with just plain Javascript.</p>
<p>Here is a video from <a href="https://www.youtube.com/@AngularUniversity" target="_blank" rel="noopener">our YouTube channel</a> demonstrating the new <code>@if</code> syntax in action:</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/W5l5r0tCsAk?si=j-XyKlBOFyUhTDa-" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<h2 id="why-don-t-we-need-to-import-if">Why don't we need to import <code>@if</code>?</h2>
<p>Notice that we don't have to import the <code>@if</code> directive from <code>@angular/common</code> into our component templates anymore.</p>
<p>This is because the <code>@if</code> syntax is part of the template engine itself, and it is <strong>not</strong> a directive.</p>
<p>The new <code>@if</code> is built-in directly into the template engine, so it's automatically available everywhere.</p>
<p>It's just like the <code>{{variable}}</code> interpolation syntax or the <code>i18n</code> syntax - you don't need to import anything in order to use it.</p>
<h2 id="why-don-t-we-need-to-use-the-syntax-anymore">Why don't we need to use the <code>*</code> syntax anymore?</h2>
<p>The <code>*</code> syntax was only used because <code>ngIf</code> was a structural directive. The <code>*</code> syntax was just syntactical sugar to make it easier for developers to use structural directives.</p>
<p>You can read more about how the old <code>*</code> syntax works under the hood <a href="https://blog.angular-university.io/angular-ngif/">here</a>.</p>
<p>The bottom line is that with <code>@if</code> we don't need to use the <code>*</code> syntax anymore, because <code>@if</code> is <em>not</em> a structural directive.</p>
<h2 id="why-is-the-new-if-syntax-better-than-ngif">Why is the new <code>@if</code> syntax better than <code>ngIf</code>?</h2>
<p>Let's quickly summarize the main reasons why <code>@if</code> is better than <code>*ngIf</code>:</p>
<ul>
<li>less verbose, more intuitive</li>
<li>no need for imports</li>
<li>supports <code>else if</code> and <code>else</code> conditions</li>
<li>no runtime overhead</li>
<li>will make the future evolution of the framework easier</li>
</ul>
<h2 id="how-to-easily-migrate-to-the-new-if-syntax">How to easily migrate to the new <code>@if</code> syntax?</h2>
<p>If you are using older versions of Angular, you can migrate to the new <code>@if</code> syntax using the Angular CLI.</p>
<p>The Angular CLI has an automated migration for upgrading all your code to the new <code>@if</code> syntax:</p>
<div class="code-block"><span class="code-lang">bash</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-bash"><code class="language-bash">ng generate @angular/core:control-flow
</code></pre></div>
<p>This command will migrate all the <code>*ngIf</code> directives in your project to the new syntax, not only for <code>@if</code> but also for the <code>@for</code> and <code>@switch</code> syntax.</p>
<h2 id="how-does-if-compare-to-hiding-elements-using-just-plain-css">How does <code>@if</code> compare to hiding elements using just plain CSS?</h2>
<p>In HTML, we can hide elements by manipulating their <code>display</code> and <code>visibility</code> properties:</p>
<ul>
<li>if we set the <code>display</code> of an element to <code>none</code> the document is not visible in the document</li>
<li>when the <code>visibility</code> of an element is set to <code>hidden</code>, the element is not shown.</li>
</ul>
<p>These all may look similar because they give the same results, but they are <strong>not</strong> the same.</p>
<p>In both cases, the hidden element still exists in the DOM, while with <code>@if</code> the hidden element doesn't exist on the DOM <strong>at all</strong>.</p>
<h2 id="multiple-nested-if-async-pipe-anti-pattern">Multiple nested <code>@if</code> async pipe anti-pattern</h2>
<p>Remember in the beginning we talked about an <code>@if</code> anti-pattern?</p>
<p>If you use RxJs in your code, I think this is well worth mentioning it because you will see it a lot, and it's directly related to <code>@if</code>.</p>
<p>This has to do with the usage of the <code>@if</code> syntax not really to show or hide an element, but just to access the values of an observable using the <code>async</code> pipe.</p>
<p>This anti-pattern is sometimes known as &quot;async pipe chaining&quot; or &quot;pyramid of doom&quot;.</p>
<p>Here is an example of this <code>@if</code> anti-pattern:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript">@<span class="token keyword">if</span> <span class="token punctuation">(</span>user$ <span class="token operator">|</span> async<span class="token punctuation">;</span> <span class="token keyword">as</span> user<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">...</span><span class="token punctuation">.</span>
    @<span class="token keyword">if</span> <span class="token punctuation">(</span>course$ <span class="token operator">|</span> async<span class="token punctuation">;</span> <span class="token keyword">as</span> course<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token operator">...</span><span class="token punctuation">.</span>
        @<span class="token keyword">if</span> <span class="token punctuation">(</span>lessons$ <span class="token operator">|</span> async<span class="token punctuation">;</span> <span class="token keyword">as</span> lesson<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token operator">...</span><span class="token punctuation">.</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>As you can see, we are using async pipe to unwrap the values of different Observables and assign them to a local template variable.</p>
<p>Then we are using the local template variable in the next <code>@if</code> statement.</p>
<p>We are repeating the use of <code>@if</code> and the async pipe, at multiple levels of the page, just for the purpose of accessing data, and nothing more.</p>
<p>This practice makes the code hard to read and maintain if several nesting levels are needed.</p>
<p>Besides, it makes the code harder to refactor, if you are doing this locally in several parts of the page instead of the whole page.</p>
<p>A good way to avoid this is to refactor your component so that it provides one single <code>data$</code> observable, containing all the data that the page needs.</p>
<p>Start by defining one interface that contains all the data that the page needs:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token keyword">interface</span> <span class="token class-name">PageData</span> <span class="token punctuation">{</span>
    user<span class="token operator">:</span> User<span class="token punctuation">;</span>
    course<span class="token operator">:</span> Course<span class="token punctuation">;</span>
    lessons<span class="token operator">:</span> Lesson<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div>
<p>Then, define a single <code>data$</code> observable that contains all the data that the page needs:</p>
<div class="code-block"><span class="code-lang">ts</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-typescript"><code class="language-typescript"><span class="token decorator"><span class="token at operator">@</span><span class="token function">Component</span></span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">Component</span> <span class="token keyword">implements</span> <span class="token class-name">OnInit</span> <span class="token punctuation">{</span>
    
  <span class="token keyword">private</span> data$<span class="token operator">:</span> Observable<span class="token operator">&lt;</span>PageData<span class="token operator">></span><span class="token punctuation">;</span>

  <span class="token function">ngOnInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">const</span> user$ <span class="token operator">=</span> <span class="token comment">// ... initialize user$ observable</span>

    <span class="token keyword">const</span> course$  <span class="token operator">=</span> <span class="token comment">// ... initialize course$ observable</span>

    <span class="token keyword">const</span> lessons$ <span class="token operator">=</span> <span class="token comment">// ... initialize lessons$ observable    </span>
    
    <span class="token keyword">this</span><span class="token punctuation">.</span>data$ <span class="token operator">=</span> <span class="token function">combineLatest</span><span class="token punctuation">(</span><span class="token punctuation">[</span>user$<span class="token punctuation">,</span> course$<span class="token punctuation">,</span> lessons$<span class="token punctuation">]</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">pipe</span><span class="token punctuation">(</span>
        <span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">[</span>user<span class="token punctuation">,</span> course<span class="token punctuation">,</span> lessons<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
          <span class="token keyword">return</span> <span class="token punctuation">{</span>
                user<span class="token punctuation">,</span> 
                course<span class="token punctuation">,</span> 
                lessons
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
    
<span class="token punctuation">}</span>
</code></pre></div>
<p>The operator <code>combineLatest</code> is just one way to create this combined Observable.</p>
<p>Finally, use <code>@if</code> in combination with the <code>async</code> pipe to unwrap the <code>data$</code> observable in the template:</p>
<div class="code-block"><span class="code-lang">html</span><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-markup"><code class="language-markup">@if (data$ | async; as data) {
    ....
    {{data.course}}

    {{data.user}}

    {{data.lessons}}
}  
</code></pre></div>
<p>As you can see, this removes all the unnecessary <code>@if</code> nesting and makes the code much more readable and maintainable.</p>
<p>If you apply this at the beginning of the template, you will have all your data easily available everywhere.</p>
<h2 id="looking-to-learn-more">Looking to learn more?</h2>
<p>To get notified when new similar posts like this are out, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>You will also get up to date news on the Angular ecosystem.</p>
<p>And if you want a deep dive into all the features of Angular core like <code>@if</code>, have a look at the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive Course</a>:</p>
<p><a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener"><img src="https://s3-us-west-1.amazonaws.com/angular-university/course-images/angular-core-in-depth-small.png" alt="" loading="lazy" decoding="async"></a></p>
<h2 id="summary">Summary</h2>
<p>In this guide, we've explored the new <code>@if</code> syntax in Angular. We've seen how it is a more concise and readable syntax, with no imports needed, and that also supports <code>else if</code> and <code>else</code> conditions, unlike the previous <code>*ngIf</code> syntax.</p>
<p>With <code>@if</code> we don't need to use the <code>NgIf</code> directive anymore, and we don't have to use the sometimes qwirky structural <code>*</code> syntax.</p>
<p>The <code>@if</code> syntax is a powerful addition to the Angular toolkit. So go and try this new control flow syntax!</p>
<p>Try the Angular CLI control flow migration on your application, and let me know in the comments below how it went.</p>
<p>If you have any questions or comments, let me know as well. I'll be happy to help!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Strictly Typed Forms (Complete Guide)</title>
      <link>https://blog.angular-university.io/angular-typed-forms/</link>
      <guid isPermaLink="false">62bc5db872335e003d34e105</guid>
      <pubDate>Thu, 30 Jun 2022 07:02:16 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Forms</category>
      <description>Learn the best way to leverage Angular Typed Forms in your projects. Add type safety to your form code by relying mostly on type inference, without needing to add extra type annotations.</description>
      <content:encoded><![CDATA[<p>The earlier versions of Angular Reactive Forms were not fully type-safe, meaning that the value emitted by the form was of type <code>any</code>, and the framework did not have a lot of information available about the types of each form control.</p>
<p>So it was easy to accidentally run into typical type-safety errors when writing Angular Forms, such as for example assigning a value of the wrong type to a form field.</p>
<p>But starting with Angular 14 and going forward, <strong>Angular has added full built-in type safety to Reactive Forms</strong>, meaning that you can get useful error messages and auto-completion when working with form values, when patching form values, and in many other situations.</p>
<p>Unlike what you might think, you <em>don't</em> have to define extra custom types, or add a ton of type annotations to your form declarations to benefit from this extra type safety.</p>
<p>You can benefit from all this extra type safety <strong>without hardly having to make any code changes</strong> to your program, as we will learn in this post.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>The Best Way to Use Angular Typed Forms</li>
<li>Avoid This Common Typed Forms Pitfall</li>
<li>Why You Don't Have to Define Extra Types (or switch to the constructor API)</li>
<li>How To Declare Nullable Fields</li>
<li>The <code>NonNullableFormBuilder</code> service</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Forms, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-forms/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know about Angular Typed Forms!</p>
<h2 id="the-best-way-to-use-angular-typed-forms">The Best Way to Use Angular Typed Forms</h2>
<p>So what is the most convenient way of using typed forms? What I like to do is to simply declare my reactive forms using the <code>FormBuilder</code> API as usual, without adding any extra type annotations, or defining extra custom types.</p>
<p>Here is a typical example of the declaration of a form for a login page with two fields (email and password):</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=01.ts"></script>
<p>As you can see, I'm just declaring this in the normal way as we have always done.</p>
<p>And believe it or not, type safety is already in place, and Angular knows that this form has two fields called email and password, both of type string!</p>
<p>To confirm this, let's check if auto-completion is working in the <code>login</code> method:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-1.png" alt="Angular Typed Forms - Auto-completion example for the form value" loading="lazy" decoding="async"></p>
<p>As we can see, we get auto-completion and type safety already, without having to do anything special!</p>
<p>Let's see another example of type safety in action, when using the form<br>
<code>patchValue()</code> API:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-2.png" alt="Angular Typed Forms - Auto-completion example for patchValue" loading="lazy" decoding="async"></p>
<p>Again we have auto-completion enabled automatically.</p>
<p>But most of all, we get useful compiler error messages, in case we are passing a value of the wrong type to a given form field:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-2-2.png" alt="Angular Typed Forms - Example of helpful compiler error messages" loading="lazy" decoding="async"></p>
<p>So how is this working? Everything is happening thanks to the Typescript compiler, and its powerful type inference mechanism.</p>
<p>The compiler is inferring the names of each form field and their types as well, <em>based on the initial value of each form field</em>.</p>
<p>Because both fields are initialized to the empty string, Angular is inferring that both fields are of type <code>string</code>.</p>
<p>To be more precise, and because all form fields are considered nullable by default, the email and password fields are inferred to have the <code>string | null</code> union type.</p>
<p>We will talk much more about nullable fields later in this post.</p>
<p>Right now, let's just realize how powerful Angular Typed Forms are: we get working type safety without having to add any extra type annotations, how cool is that?</p>
<p>But we only get this benefit if we use the <code>FormBuilder</code> as it was designed to be used.</p>
<p>Let's now see a couple of examples of when things could go wrong.</p>
<h2 id="avoid-this-common-typed-forms-pitfall">Avoid This Common Typed Forms Pitfall</h2>
<p>While trying to leverage typed forms, a very common pitfall that you want to avoid is to declare your form member variables as having the explicit type<br>
<code>FormGroup</code>, like so:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=02.ts"></script>
<p>What could be more natural, right? We are declaring the <code>form</code> member variable, and initializing it on <code>ngOnInit</code>, which is a super-common and well-established pattern.</p>
<p>This way of declaring forms might seem natural, and you might have been used to declare forms in this way in your code.</p>
<p>But now, this approach is no longer advised as it prevents you from benefitting from full form type safety.</p>
<p>See for yourself, we now no longer get auto-completion when accessing the form value!</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-3.png" alt="Angular Typed Forms - Auto-completion gone the form value, due to wrong declaration of the form member variable" loading="lazy" decoding="async"></p>
<p>And when using <code>patchValue</code>, we no longer get suggestions for form field names:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-4.png" alt="Angular Typed Forms - Auto-completion gone the form value, due to wrong declaration of the form member variable" loading="lazy" decoding="async"></p>
<p>Besides not having auto-completion, we will also <em>not</em> get helpful error messages from the compiler when assigning wrong values to a field, unlike before.</p>
<h4 id="why-is-this-not-working">Why is this not working?</h4>
<p>This way of declaring forms does not allow for our forms to be type safe, because we are declaring the form as of type <code>FormGroup</code>, which implicitly defaults to <code>FormGroup&lt;any&gt;</code>, meaning that the form value will be of type <code>any</code>.</p>
<p>As you know, <code>any</code> essentially means that the compiler does not have any type information about the form value, so all forms of type safety are turned off and the form is no longer type safe.</p>
<p>Notice that Typescript is still inferring all the type information from the form declaration, but then we are throwing that information away by assigning the form declaration to a plain <code>FormGroup</code> variable.</p>
<p>In order to avoid this issue and still have fully type-safe forms, simply use the method we first showed in this post, and let the type of the form variable be fully determined by type inference.</p>
<h2 id="why-you-don-t-have-to-define-extra-types-or-switch-to-the-constructor-api">Why You Don't Have to Define Extra Types (or switch to the constructor API)</h2>
<p>In order to make type-safe forms work, you also don't have to declare an explicit form type like this:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=03.ts"></script>
<p>This extra type is not necessary. It's more readable and less verbose to simply rely on type inference instead.</p>
<p>You also <em>don't</em> have to switch to the constructor API to benefit from type safety.</p>
<p>For example, you <em>don't</em> have to write your form declarations in this way to benefit from type safety:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=09.ts"></script>
<p>It's not that this is wrong or anything, but the <code>FormBuilder</code> API is just as type safe and less verbose, so I tend to prefer it.</p>
<h2 id="how-to-declare-nullable-fields">How To Declare Nullable Fields</h2>
<p>By default, all form fields are considered to be nullable. And this is because when we call the form <code>reset()</code> method, Angular will set all of the form fields to <code>null</code>.</p>
<p>This default behavior has been in there in Angular since the beginning, so that is why we need to consider every field as nullable, unless we configure it otherwise.</p>
<p>We can also optionally declare a form field as non-nullable, meaning that the form field will be reset to its initial value instead of <code>null</code>.</p>
<p>One of the ways of doing this is by using the constructor API:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=05.ts"></script>
<p>In this example, we have declared the email field as non-nullable, while the password field remains nullable.</p>
<p>But this can also be done using the <code>FormBuilder</code> API, with the same results:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=06.ts"></script>
<p>Let's now see what happens when we call reset in our form:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=07.ts"></script>
<p>And here is the generated output in the browser's console:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-5.png" alt="Angular Typed Forms - example of reset of a non-nullable field" loading="lazy" decoding="async"></p>
<p>As we can see, the email field is now being reset to its initial value, instead of null.</p>
<h2 id="the-nonnullableformbuilder-service">The <code>NonNullableFormBuilder</code> service</h2>
<p>If you are building a large form where <em>all</em> of its fields are non-nullable, then marking the fields as non-nullable one by one could become quite verbose.</p>
<p>A simpler way to do that is to switch to using the <code>NonNullableFormBuilder</code> service, instead of <code>FormBuilder</code>.</p>
<p>Using this service, we can simply declare our fields without mentioning their nullability, and <strong>every field will be considered nullable by default</strong>:</p>
<script src="https://gist.github.com/jhades/2d678f0140a013ec3d0b5eb2e450944c.js?file=08.ts"></script>
<p>And here is what the output of the console looks like after calling <code>reset</code> on this new form:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-typed-forms/angular-typed-forms-6.png" alt="Angular Typed Forms - example of reset of a non-nullable field" loading="lazy" decoding="async"></p>
<p>As you can see, now <em>all</em> of the fields are considered non-nullable, as they are being reset to their initial value as expected (and not to null).</p>
<h2 id="summary">Summary</h2>
<p>I hope that this post helped in understanding how the Angular Typed Forms feature works, and how we can best use it.</p>
<p>This feature is really super convenient!</p>
<p>Without any extra ceremony in our code like extra type annotations, and without having to switch to the constructor API, we now have full type-safety and auto-completion in our form-related code.</p>
<p>Everything happens almost by magic, due to the power of Typescript type inference.</p>
<p>In summary, I highly recommend that you start leveraging Typed Forms in your code. There is no downside to it, and it will help you prevent countless bugs and make your form code that much more maintainable in the long run.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular Forms (both Template-Driven and Reactive), we recommend checking the <a href="https://angular-university.io/course/angular-forms-course" target="_blank" rel="noopener">Angular Forms In Depth</a> course, where Typed Forms are covered in detail.</p>
<p>Also, if you have some questions or comments please let me know in the comment section below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Responsive Design: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-responsive-design/</link>
      <guid isPermaLink="false">62178adf2d353f003d628f64</guid>
      <pubDate>Thu, 24 Feb 2022 16:39:16 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Material</category>
      <description>Learn how to make your Angular components and applications responsive without having to write a single media query.
</description>
      <content:encoded><![CDATA[<p>If you are building applications with Angular (with or without Angular Material), did you know that you have available a very practical way of making your layout responsive <strong>without having to write any media queries</strong> yourself?</p>
<p>Yes, that's right, no media queries. 😉</p>
<p>Not that there is anything fundamentally wrong with writing our own media queries, it's just that I find that it can become quickly messy, unpractical and hard to maintain.</p>
<p>So if I can, I prefer to avoid it or at least minimize the number of media queries that I have to write, and Angular allows us to do just that.</p>
<p>So how do we make an Angular component or application responsive?</p>
<p><strong>Follow these steps to implement a responsive design with Angular:</strong></p>
<ul>
<li><strong>use the Angular BreakpointObserver to detect the size of the current device</strong></li>
<li><strong>set member variables in your component that allow you to show or hide certain elements depending on the screen size</strong></li>
<li><strong>Set responsive CSS classes in your component like <code>is-phone-portrait</code> depending on the screen size</strong></li>
<li><strong>Use these special classes to make the CSS of your component responsive without writing media queries</strong></li>
</ul>
<p>For the full details on exactly how to do this, check out the rest of the post.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>The BreakpointObserver Service</li>
<li>Using layout-related flags to show or hide responsive elements</li>
<li>Writing CSS that only applies to certain screen sizes (without media queries)</li>
<li>Summary</li>
</ul>
<p>So without further ado, let's get started learning everything that we need to know for making your Angular application responsive!</p>
<h2 id="the-breakpointobserver-service">The BreakpointObserver Service</h2>
<p>The key to making our application responsive without writing our own media queries is the <a href="https://blog.angular-university.io/angular-responsive-design/BreakpointObserver">Angular CDK BreakpointObserver</a> service.</p>
<p>This service provides us with an observable-based API that notifies its subscribers of the current dimensions of the screen, and any changes to the screen orientation caused by switching the device from landscape to portrait mode.</p>
<p>This service will also emit new values when we simulate different screen sizes using the dev tools, which is ideal for testing multiple layouts during development.</p>
<p>Notice that this service is part of the Angular Component Development Kit and not part of Angular Material directly.</p>
<p>You can use it with Angular Material, but you can also use it without it.</p>
<p>Using this service does not imply having to import a lot of code into your application, as the CDK is very modular.</p>
<p>So how does this service work?</p>
<p>The <code>BreakpointObserver</code> service comes with a series of pre-built CSS breakpoints, that identify different types of devices and screen form factors:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=01.ts"></script>
<p>Each of these breakpoints corresponds to a CSS media query, carefully written and researched to accurately match a very broad range of devices.</p>
<p>This is a complete list, but I find that most of the time <code>TabletPortrait</code>,<br>
<code>TabletLandscape</code>, <code>HandsetPortrait</code> and <code>HandsetLandscape</code> is all we need for most use cases.</p>
<p>If you want to know exactly to which CSS media query each breakpoint corresponds to, you can simply print them out to the screen, as the breakpoints are just strings containing the text of the media query.</p>
<p>Here is the result that you will get in the console.</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=02.ts"></script>
<p>The good news is that you actually don't have to worry about these media queries <em>at all</em>.</p>
<p>You will never have to maintain these CSS media queries yourself:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">Web (min-width: 840px) and (orientation: portrait), (min-width: 1280px) and (orientation: landscape)

WebLandscape (min-width: 1280px) and (orientation: landscape)

WebPortrait (min-width: 840px) and (orientation: portrait)

Tablet (min-width: 600px) and (max-width: 839.98px) and (orientation: portrait), (min-width: 960px) and (max-width: 1279.98px) and (orientation: landscape)

TabletPortrait (min-width: 600px) and (max-width: 839.98px) and (orientation: portrait)

TabletLandscape (min-width: 960px) and (max-width: 1279.98px) and (orientation: landscape)

Handset (max-width: 599.98px) and (orientation: portrait), (max-width: 959.98px) and (orientation: landscape)

HandsetLandscape (max-width: 959.98px) and (orientation: landscape)

HandsetPortrait (max-width: 599.98px) and (orientation: portrait)

XSmall (max-width: 599.98px)

Small (min-width: 600px) and (max-width: 959.98px)

Medium (min-width: 960px) and (max-width: 1279.98px)

Large (min-width: 1280px) and (max-width: 1919.98px)

XLarge (min-width: 1920px)
</code></pre></div>
<p>For example, <code>TabletLandscape</code> and <code>TabletPortrait</code> correspond perfectly to a standard size iPad screen.</p>
<p>And the <code>Hanset</code> breakpoints correspond to mobile phones such as iPhone or Android phones.</p>
<h2 id="how-does-the-breakpointobserver-service-work">How does the <code>BreakpointObserver</code> service work?</h2>
<p>The <code>BreakpointObserver</code> provides us with an observable-based API that allows us to be notified whenever any of these breakpoints are matched by the current device.</p>
<p>For example, here is how we subscribe to the service to get notified when the screen matches the <code>HandsetLandscape</code> breakpoint:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=03.ts"></script>
<p>If you start the application on a normal size desktop, you will see that nothing gets printed out to the console, and this is normal.</p>
<p>But you can simulate mobile devices using the Chrome Dev Tools, by using the Device toolbar:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/responsive-design-angular-1.jpg" alt="Selecting a mobile device using the Chrome dev tools" loading="lazy" decoding="async"></p>
<p>The button highlighted in red will turn on the device toolbar, which allows you to select the size of the screen.</p>
<p>In this case, we set the screen to the same dimensions as an iPhone in landscape mode.</p>
<p>And as we can see in the console, this time around the breakpoint was triggered as expected.</p>
<p>As you toggle on and off the Chrome dev tools or you switch screen sizes using the device toolbar, you will see that a new value gets emitted by the breakpoint observer.</p>
<p>You can also use the <code>BreakpointObserver</code> to subscribe to multiple breakpoints at the same time:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=04.ts"></script>
<p>Notice that there is a breakpoints map emitted by the <code>BreakpointObserver</code> service, that contains all the currently matching breakpoints, and we can test for each breakpoint separately.</p>
<p>As we can see, this service provides the fundamental building blocks for making our Angular components responsive.</p>
<p>But how do we use it in practice? There are a couple of ways.</p>
<h2 id="using-layout-related-flags-to-show-or-hide-responsive-elements">Using layout-related flags to show or hide responsive elements</h2>
<p>One of the simples things that we can do, is to adapt certain member variables of our component according to the responsive breakpoints that are matched.</p>
<p>For example, let's say that we have a component that needs to hide a side menu if the device is a phone or tablet in portrait mode.</p>
<p>We could adapt the UI by setting the value of a <code>hideSideMenu</code> boolean member variable according to the current breakpoints:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=05.ts"></script>
<p>Notice how we need to reset the value of <code>hideSideMenu</code> when receiving a new set of matching breakpoints. We need to set this value back to its default value, in case the device no longer matches any of the breakpoints.</p>
<p>We can then use the <code>hideSideMenu</code> flag to show or hide the side menu in the component template using <code>ngIf</code>:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=06.html"></script>
<p>Instead of a boolean flag, we can also set a variable that defines the number of columns in a grid, the height of an element or anything else we need.</p>
<p>But what if we want to adapt the component styling according to the device?</p>
<h2 id="writing-css-that-only-applies-to-certain-screen-sizes-without-media-queries">Writing CSS that only applies to certain screen sizes (without media queries)</h2>
<p>Many times, we still want to be able to control our component behavior using plain CSS.</p>
<p>For example, we would like to be able to remove certain margins and padding on a mobile device, due to the lack of space.</p>
<p>We can still do this without having to write media queries in our components, by creating a few layout-specific boolean member variables in our component.</p>
<p>For example, let's imagine that we want our component to apply certain CSS styles only if the screen is in phone portrait mode (usually the most restrictive format).</p>
<p>We would start by adding a boolean flag <code>isPhonePortrait</code> to our component:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=07.ts"></script>
<p>Then, we can use this flag to apply a special <code>is-phone-portrait</code> to a container div that wraps the whole content of our component, using <code>ngClass</code>:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=08.html"></script>
<p>Using this special CSS class, it's now very simple to add responsive styles to the CSS of our component, without having to write media queries:</p>
<script src="https://gist.github.com/jhades/6e2945497d38b1d794172bd728e47bba.js?file=09.scss"></script>
<h2 id="summary">Summary</h2>
<p>As we could see, the <code>BreakpointObserver</code> service of the Angular Cdk makes it super simple to make our Angular components responsive, without having to write a single media query.</p>
<p>Again, not that there is anything fundamentally wrong with adding media queries directly to your components CSS, it's just that I find that this approach is easier to read and maintain in the long term.</p>
<p>For example, if you want to search for all the specific styles in your application that target a phone in portrait mode, you can just search for <code>is-phone-portrait</code>, as opposed to searching for a media query where it's easy to miss certain styles due to formatting, spacing, indenting, etc.</p>
<p>I also find that if the responsive CSS of each component is written this way, its just easier to read and understand it, which helps the codebase remain maintainable over time.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular Material, we recommend checking the <a href="https://angular-university.io/course/angular-material-course" target="_blank" rel="noopener">Angular Material In Depth</a> course, where responsive design is covered in detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Material Datepicker: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-material-datepicker/</link>
      <guid isPermaLink="false">6203cd894875f4003b2a9537</guid>
      <pubDate>Thu, 10 Feb 2022 12:15:31 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>Complete guided tour to the Angular Material Datepicker component, from the most commonly used features to the most advanced ones.</description>
      <content:encoded><![CDATA[<p>One of the most commonly used form components that we need for building Applications with Angular is some form of datepicker.</p>
<p>If you are building an Angular application, there is no need to use third-party components that are not Angular-based, such as for example the jQuery datepicker.</p>
<p>Instead, as part of the Angular Material library you have a powerful datepicker written in Angular and ready to be used, that is responsive and that has been battle-tested and used in thousands of applications.</p>
<p>I'm talking about the <a href="https://material.angular.io/components/datepicker/overview" target="_blank" rel="noopener">Angular Material datepicker</a>, that is jam-packed with <strong>tons of useful options that you might not be aware of</strong>.</p>
<p>In this post, we are going to guide you through this datepicker component in detail, covering everything from the simplest to the most advanced features.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>Setting up the Angular Material Datepicker</li>
<li>Adding a modal calendar to the datepicker</li>
<li>Opening the calendar dialog when clicking on the input</li>
<li>Configuring the mat-datepicker-toggle icon</li>
<li>Preventing the user from manually typing in dates</li>
<li>Configuring the starting view mode of the calendar</li>
<li>Configuring the starting date of the calendar</li>
<li>Limiting the input range of a datepicker</li>
<li>Custom validation of dates with matDatepickerFilter</li>
<li>Configuring the look and feel of the calendar</li>
<li>Adding custom styles to certain dates in the calendar</li>
<li>Support for mobile devices</li>
<li>Using the calendar in standalone mode</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Material, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-material/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know about the Angular Material Datepicker!</p>
<h2 id="setting-up-the-angular-material-datepicker">Setting up the Angular Material Datepicker</h2>
<p>Here is an example of a typical datepicker:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example.png" alt="Angular Material Datepicker Example" loading="lazy" decoding="async"></p>
<p>As we can see, this datepicker is composed of 3 separate elements:</p>
<ul>
<li>an input text field, used to type in the date manually</li>
<li>a calendar modal dialog, that shows up next to the input field and allows the user to choose a date visually</li>
<li>a calendar icon, that you can use to open or close the calendar dialog</li>
</ul>
<p>Let's then create a datepicker by adding these 3 elements progressively, and explain how everything is connected together.</p>
<p>Let's start with the plain input field:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=01.html"></script>
<p>As we can see, this is just a plain Angular Material input field, with no date input capabilities yet.</p>
<p>The field is linked to a form control via the Angular Forms <code>formControlName</code> directive, and the name of the date field is <code>releasedAt</code>.</p>
<p>The field has an outline appearance, so that we can see that nice border around the input, and notice the use of the <code>matInput</code> directive.</p>
<p>Without this directive applied properly to the HTML input, the input component will not work correctly.</p>
<h3 id="adding-a-modal-calendar-to-the-datepicker">Adding a modal calendar to the datepicker</h3>
<p>To this plain input, we are now going to add a modal calendar element next to it:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=02.html"></script>
<p>Notice the use of the <code>[matDatepicker]</code> directive, that links the input field with the modal element.</p>
<p>If you try this out now, you won't see anything different at this stage, because the modal calendar is hidden by default.</p>
<p>To be able to open it or close it, we need a toggle button. We are going to add it to the end of the input field as a suffix, and connect it with the modal calendar:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=03.html"></script>
<p>Notice the use of the <code>[for]</code> directive, that links the toggle button to the datepicker.</p>
<p>And with this, we have now finished the minimal set up of our datepicker, and we can now open the calendar and use it to choose a date, it's that simple!</p>
<p>But this is just the basic usage of the datepicker component. In the rest of this post, we are going to cover a ton of commonly used features and configuration options that you have available for the datepicker.</p>
<h2 id="opening-the-calendar-dialog-when-clicking-on-the-input">Opening the calendar dialog when clicking on the input</h2>
<p>First, let's start with a very common feature that you might be asked to implement, which is to automatically open the calendar once the corresponding input gets clicked.</p>
<p>You can do just by adding a normal event click handler, and calling the <code>calendar.open()</code> method:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=05.html"></script>
<h2 id="configuring-the-mat-datepicker-toggle-icon">Configuring the mat-datepicker-toggle icon</h2>
<p>Sometimes you might want to configure the look and feel of the toogle calendar button.</p>
<p>Notice that the calendar toggle shows up to the right of the input field, and this is due to the use of the <code>matSuffix</code> directive.</p>
<p>The <code>matSuffix</code> is a configuration directive for the material input field, that will ensure that the calendar icon is added at the end (to the right) of the input field.</p>
<p>If instead you want to show the calendar icon to the left of the input field, you can do so by using <code>matPrefix</code> instead of <code>matSuffix</code>.</p>
<p>Here is what your datepicker will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-2.png" alt="Angular Material Datepicker " loading="lazy" decoding="async"></p>
<p>Besides configuring the positioning of the icon, you can also configure the icon itself.</p>
<p>By default, the <code>mat-datepicker-toggle</code> will show up as a calendar icon, but you can choose to use any other icon of the Material design icon library.</p>
<p>For example, there are tons of other calendar-related icons that you might prefer instead: <a href="https://fonts.google.com/icons?selected=Material+Icons&amp;icon.query=calendar" target="_blank" rel="noopener">Material design calendar icons</a>.</p>
<p>Here is how you can use an alternative calendar icon:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=04.html"></script>
<p>Notice the use of the <code>matDatepickerToggleIcon</code> directive, without it this would not work.</p>
<p>And here is what your calendar will look like with the new icon:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-3.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="preventing-the-user-from-manually-typing-in-dates">Preventing the user from manually typing in dates</h2>
<p>Normally you want to allow the user to be able to input dates in the two different ways: manually via the input field and visually via the calendar.</p>
<p>But if you want, you can disable the input field, and that will prevent the user from typing in some date.</p>
<p>The problem is, both the toggle button and the calendar will inherit the disabled state, so the user won't be able to enter any date at all.</p>
<p>But you can override this, and allow the user to still enter a date visually using the modal calendar:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=06.html"></script>
<p>As you can see, you need to override the disabled property on <em>both</em> the toggle button and the calendar in order for this to work.</p>
<h2 id="configuring-the-starting-view-mode-of-the-calendar">Configuring the starting view mode of the calendar</h2>
<p>By default, the calendar dialog opens with a monthly view of the month associated with the date value.</p>
<p>If no value is set, today's date will be shown as highlighted in the current month.</p>
<p>For a lot of dates this is the intended behaviour, but for other dates it would be better to start with a yearly view.</p>
<p>For example, if it's a birthday date, starting with today's date does not make a lot of sense. Instead, we would prefer to first select a decade, then a year, then a month, etc.</p>
<p>We can configure the view mode of the calendar by using the <code>startView</code> property:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=07.html"></script>
<p>And here is what the calendar yearly view will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-4.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<p>And if instead of <code>year</code>, we use <code>multi-year</code>, this is what the calendar will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-5.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="configuring-the-starting-date-of-the-calendar">Configuring the starting date of the calendar</h2>
<p>It's also possible to set the starting date of the calendar to a different value than the value of the form control.</p>
<p>We need to start by defining a member variable in our controller with the start date:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">startDate = new Date(2010, 0, 1)
</code></pre></div>
<p>Then all we have to do is to pass the start date to the date picker:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=10.html"></script>
<h2 id="limiting-the-input-range-of-a-datepicker">Limiting the input range of a datepicker</h2>
<p>Sometimes we want to restrict what dates the user can enter using the calendar.</p>
<p>If we want to define an acceptable range of dates, we need to define a couple of member variables in our component:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">minDate = new Date(2010, 0, 3); 
maxDate = new Date(2010, 0, 15);
</code></pre></div>
<p>Then we need to pass these limits using the <code>[min]</code> and <code>[max]</code> directives to the <code>matInput</code> directive:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=15.html"></script>
<p>And this what the datepicker will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-11.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<p>As we can see, the dates outside of the valid range are disabled, so the user can't click on them.</p>
<h2 id="custom-validation-of-dates-with-matdatepickerfilter">Custom validation of dates with matDatepickerFilter</h2>
<p>Sometimes we need a bit more control about which dates are valid or not.</p>
<p>For example, imagine that we have a situation where the user should only be able to pick Mondays from the calendar.</p>
<p>To implement this, the first thing that we need is a date filter function:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=16.html"></script>
<p>This function returns true if the date is a Monday, and false otherwise. Now all we have to do is to plug it into the datepicker:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=17.html"></script>
<p>And this is what the calendar will look like, as we can see only Mondays are enabled:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-12.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="configuring-the-look-and-feel-of-the-calendar">Configuring the look and feel of the calendar</h2>
<p>By default, the datepicker will use the primary palette of our Angular Material theme to highlight the selected date.</p>
<p>But it's also possible to use one of the alternative palettes, such as the accent palette or the danger pallete.</p>
<p>This is how we configure the calendar to use the accent palette:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=11.html"></script>
<p>And this is how the calendar will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-8.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<p>If instead we want to use the danger palette, we can use <code>warn</code> instead of<br>
<code>accent</code> as the color property.</p>
<h2 id="adding-custom-styles-to-certain-dates-in-the-calendar">Adding custom styles to certain dates in the calendar</h2>
<p>Sometimes we need a bit more control over the styling of each date cell.</p>
<p>Imagine an air flight booking website, where we would like to highlight the period between the start and end of the flight with a different background color.</p>
<p>Or to take a simpler example, let's say that we want to highlight every 1st day of the month with a different color in the month view only.</p>
<p>The first thing that we need to do is to create a date class function:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=12.html"></script>
<p>This function returns the <code>highlight-date</code> CSS class only for the first day of each month, and no CSS classes otherwise.</p>
<p>Now, all we have to do is to plug it into the datepicker like this:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=14.html"></script>
<p>And this is what the datepicker will look like, in the monthy view:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-10.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="support-for-mobile-devices">Support for mobile devices</h2>
<p>The default behavior of the datepicker is ideal for desktop devices, and it works on mobile too, but the dates in the modal dialog might be too close to each other for the user to comfortably select them.</p>
<p>But if you anticipate that your application is going to be used mostly on mobile, and you want to make inputting dates easier for the user, you can activate a larger, touch-friendly interface for the datepicker.</p>
<p>You can do so by setting the <code>touchUi</code> property to true:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=08.html"></script>
<p>This property will make the modal dialog much bigger and more mobile-friendly:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-6.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="using-the-calendar-in-standalone-mode">Using the calendar in standalone mode</h2>
<p>Sometimes, you just want to show to the user a calendar with an associated input field, so that the user can choose a date directly inline in the page without typing it in manually.</p>
<p>You can do so in the following way, by using the <code>mat-calendar</code> component:</p>
<script src="https://gist.github.com/jhades/0509b6be014c3e8a6d93d2cc1d87c5a8.js?file=09.html"></script>
<p>And this is what your inline calendar will look like:</p>
<p><img src="https://angular-university.s3.us-west-1.amazonaws.com/blog-images/angular-material/angular-material-datepicker-example-7.png" alt="Angular Material Datepicker" loading="lazy" decoding="async"></p>
<h2 id="summary">Summary</h2>
<p>I hope that you have enjoyed this post. If you would like to learn a lot more about Angular Material, we recommend checking the <a href="https://angular-university.io/course/angular-material-course" target="_blank" rel="noopener">Angular Material In Depth</a> course, where all sorts of Angular Material components and best practices are covered in great detail:</p>
<p><a href="https://angular-university.io/course/angular-material-course" target="_blank" rel="noopener"><img src="https://angular-university.s3-us-west-1.amazonaws.com/course-images/angular-material-course-1.jpg" alt="" loading="lazy" decoding="async"></a></p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular Material and other Angular topics, I invite you to subscribe to my newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Dependency Injection: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-dependency-injection/</link>
      <guid isPermaLink="false">60ffc849b90f9e003b92020d</guid>
      <pubDate>Wed, 28 Jul 2021 14:39:28 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>Everything that you need to know in practice to use the Angular dependency injection system, all in one place. All of its advanced concepts are explained in a practical and easy-to-understand way, with examples.</description>
      <content:encoded><![CDATA[<p>One of the most powerful and distinguishing features of Angular is its built-in dependency injection system.</p>
<p>Most of the times, dependency injection just works, and we use it almost without thinking thanks to its very convenient and intuitive Angular API.</p>
<p>But there are other times, where <em>we might need to dig a lot deeper</em> into the dependency injection system, and configure it manually.</p>
<p>This in-depth knowledge of dependency injection will be necessary for example in these circumstances:</p>
<ul>
<li>to troubleshoot some weird dependency injection error</li>
<li>to configure manually the dependencies for a unit test</li>
<li>to understand the unusual dependency injection configuration of some third-party module</li>
<li>to create a third-party module that is going to be shipped and used in multiple applications</li>
<li>to design your application in a more modular way</li>
<li>to ensure that different parts of your application are well isolated and can't interfere with each other</li>
</ul>
<p>In this guide, we are going to <strong>understand exactly how Angular dependency injection works</strong>, as we are going to cover all its configuration options and learn when to use each feature and why.</p>
<p>We are going to do this in a very practical and easy-to-understand way, by implementing our own providers and injection tokens from scratch, as an exercise, and covering all features with an example-based approach.</p>
<p>This deep understanding of the Angular dependency injection system is going to prove invaluable to you as an Angular developer over time. 😉</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>Introduction to Dependency Injection</li>
<li>How to set up dependency injection from scratch in Angular?</li>
<li>What is an Angular Dependency Injection Provider?</li>
<li>How to write our own provider?</li>
<li>Introduction to Injection Tokens</li>
<li>How to manually configure a provider?</li>
<li>Using class names as Injection Tokens</li>
<li>Simplified configuration of providers: useClass</li>
<li>Understanding Angular multiple value dependencies</li>
<li>When to use an <code>useExisting</code> provider</li>
<li>Understanding Angular Hierarchical Dependency Injection</li>
<li>What are the advantages of Hierarchical Dependency Injection?</li>
<li>Components Hierarchical Dependency Injection - an example</li>
<li>Modules Hierarchical Dependency Injection - an example</li>
<li>Modules vs Components Dependency Injection Hierarchies</li>
<li>Configuring the Dependency Injection Resolution mechanism</li>
<li>Understanding the @Optional decorator</li>
<li>Understanding the @SkipSelf decorator</li>
<li>Understanding the @Self decorator</li>
<li>Understanding the @Host decorator</li>
<li>What are Tree-Shakeable Providers?</li>
<li>Understanding Tree-Shakeable Providers via an example</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular core features, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-core/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know about Angular dependency injection! 😃</p>
<h2 id="introduction-to-dependency-injection">Introduction to Dependency Injection</h2>
<p>So what exactly is dependency injection?</p>
<p>When you are developing a smaller part of your system, like a module or a class, you are going to need some external dependencies.</p>
<p>For example, you might need an HTTP service to make backend calls, as well as some other dependencies.</p>
<p>You might even be tempted to create your own dependencies locally every time that you need them, like this:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=01.ts"></script>
<p>This might look like a very simple solution, but there is a problem with this code: <strong>it's super hard to test</strong>.</p>
<p>Because the code knows about its own dependencies and creates them directly, it's impossible with this version of the code to replace for example the actual HTTP client with a mock HTTP client, and unit test the class.</p>
<p>Notice that this class knows not only how to create its own dependencies, but it also knows about the dependencies of its dependencies 🙄, meaning it knows about the dependencies of the HTTPClient class as well.</p>
<p>With the way that this code is written, it's basically impossible to replace at runtime this dependency with an alternative version, for example:</p>
<ul>
<li>for testing purposes</li>
<li>but also because you might need different HTTP clients in different runtime environments, like for example on the server vs the browser.</li>
</ul>
<p>Compare this to an alternative version of this same class, that <em>does</em> use dependency injection:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=02.ts"></script>
<p>As you can see in this new version, this class simply <em>does not know</em> how to create its http dependency.</p>
<p>This new version of the class simply receives all the dependencies that it needs as input arguments in the constructor, and that's it! 😃</p>
<p>This new version of the class just knows how to use its dependencies to perform a concrete task, but it does not know how that dependency works internally, how it was created, and what are its dependencies.</p>
<p>The code to create the dependency has been moved out of the class and placed somewhere else in your code base, thanks to the use of the <code>@Injectable()</code> decorator.</p>
<p>With this new class, it's super easy to:</p>
<ul>
<li>replace an implementation of a dependency for testing purposes</li>
<li>to support multiple runtime environments</li>
<li>to provide new versions of a service to a third-party that uses your service in their code base, .etc.</li>
</ul>
<p>This technique of just receiving your dependencies as inputs without knowing how they work internally or how they were created is aptly named <em>dependency injection</em>, and it's one of the cornerstones of Angular.</p>
<p>Let's now learn exactly how Angular dependency injection works.</p>
<h2 id="how-to-set-up-dependency-injection-from-scratch-in-angular">How to set up dependency injection from scratch in Angular?</h2>
<p>The best way to understand dependency injection in Angular, is to take a plain Typescript class without any decorators applied to it, and turn it into an Angular injectable service <em>manually</em>, from scratch.</p>
<p>It's much easier than it sounds. 😃</p>
<p>Let's start with a very simple service class, with no <code>@Injectable()</code> decorator applied to it:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=03.ts"></script>
<p>As we can see, this is just a plain Typescript class, that expects some dependencies to be injected in its constructor.</p>
<p>But this class is in <em>no way linked</em> to the Angular dependency injection system at all.</p>
<p>Let's see what happens if we now try to inject this class as a dependency into the constructor of another class:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=04.ts"></script>
<p>As we can see, we are trying to inject <em>an instance</em> of this class as a dependency.</p>
<p>But our class is not linked to the Angular dependency injection system, so what part of our program will know how to call the <code>CoursesService</code> constructor to create an instance of that class and pass it as a dependency?</p>
<p>The answer is simple: <em>nobody</em>, and so we will get an error! 😉</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none"> NullInjectorError: No provider for CoursesService!
</code></pre></div>
<p>Notice the error message: apparently something known as <em>a provider</em> is missing.</p>
<p>You probably have seen a similar message before, it happens very commonly during development.</p>
<p>Let's now understand exactly what this message means, and how to troubleshoot it.</p>
<h2 id="what-is-an-angular-dependency-injection-provider">What is an Angular Dependency Injection Provider?</h2>
<p>The error message &quot;no provider&quot; means simply that the Angular dependency injection system can't instantiate a given dependency, because it <em>does not know</em> how to create it.</p>
<p>In order for Angular to know how to create a dependency such as for example the <code>CoursesService</code> instance injected in the <code>CourseCardComponent</code> constructor, it needs what is known as a provider factory function.</p>
<p>A provider factory function is simply a plain function that Angular can call in order to create a dependency, it's as simple as that: <em>it's just a function</em>. 👍</p>
<p>That provider factory function can even be created implicitly by Angular using some simple conventions that we will talk about, and that is actually what usually happens for most of our dependencies.</p>
<p>But we can also write that function ourselves if needed.</p>
<p>In any case, it's important to understand that for every single dependency in your application, be it a service or a component or anything else, there is somewhere a plain function that is being called that knows how to create your dependency.</p>
<h3 id="how-to-write-our-own-provider">How to write our own provider?</h3>
<p>To really understand what a provider is, let's simply write our own provider factory function for the <code>CoursesService</code> class:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=05.ts"></script>
<p>As you can see, this is just a plain function that takes as input any dependencies that <code>CoursesService</code> needs.</p>
<p>This provider factory function will then call the <code>CoursesService</code> constructor manually, pass all the needed dependencies, and return the new <code>CoursesService</code> instance as the output.</p>
<p>So any time that the Angular dependency injection system needs an instance of <code>CoursesService</code>, all it needs to do is to call this function!</p>
<p>This looks very simple, but the problem is the Angular dependency injection system does not know about this function <em>yet</em>.</p>
<p>More important than that, even if Angular knew about this function, how would it know that it needs to call it to inject this particular dependency:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=04.ts"></script>
<p>I mean, there is no way for Angular to make the link between this injected instance of <code>CoursesService</code> and the provider factory function, right?</p>
<h2 id="introduction-to-injection-tokens">Introduction to Injection Tokens</h2>
<p>So how does Angular know what to inject where, and what provider factory functions to call to create which dependency?</p>
<p>Angular needs to be able to classify dependencies somehow, in order to identify that a given set of dependencies are <em>all of the same type</em>.</p>
<p>In order to uniquely identify a category of dependencies, we can define what is known as an Angular injection token.</p>
<p>Here is how we create our injection token manually, for our <code>CoursesService</code> dependency:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=06.ts"></script>
<p>This injection token object will be used to clearly identify our <code>CoursesService</code> dependency in the dependency injection system.</p>
<p>The dependency injection token is an object, so in that sense it's unique, unlike a string for example.</p>
<p>So this token object can be used to uniquely identify a set of dependencies.</p>
<p>So how do we use it?</p>
<h2 id="how-to-manually-configure-a-provider">How to manually configure a provider?</h2>
<p>Now that we have both the provider factory function and the injection token, we can configure a provider in the Angular dependency injection system, that will know how to create instances of <code>CoursesService</code> if needed.</p>
<p>The provider itself is simply a configuration object, that we pass on to the<br>
<code>providers</code> array of a module or component:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=07.ts"></script>
<p>As we can see, this manually configured provider needs the following things defined:</p>
<ul>
<li>
<p><code>useFactory</code>: this should contain a reference to the provider factory function, that Angular will call when needed to create dependencies and inject them</p>
</li>
<li>
<p><code>provide</code>: this contains the injection token linked to this type of dependency. The injection token will help Angular determine <em>when</em> a given provider factory function should be called or not</p>
</li>
<li>
<p><code>deps</code>: this array contains any dependencies that the <code>useFactory</code> function needs in order to run, in this case the HTTP client</p>
</li>
</ul>
<p>So now Angular knows how to create instances of <code>CoursesService</code>, right?</p>
<p>Let's see what happens if we now try to inject an instance of <code>CoursesService</code> in our application:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=04.ts"></script>
<p>We might be a bit surprised to see that the same error message still occurs:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">NullInjectorError: No provider for CoursesService!
</code></pre></div>
<p>So what is going on here? Didn't we just <em>define</em> the provider?</p>
<p>Well, yes, but there is no way for Angular to know that it needs to use our particular provider factory function when attempting to create this dependency, right?</p>
<p>So how do we make that link?</p>
<p>We need to explicitly tell Angular that <em>it should</em> use our provider to create this dependency.</p>
<p>We can do so by using the <code>@Inject</code> annotation, everywhere where <code>CoursesService</code> is being injected:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=08.ts"></script>
<p>As we can see, the explicit use of the <code>@Inject</code> decorator allows us to tell Angular that in order to create this dependency, it needs to use the specific provider linked to the <code>COURSES_SERVICE_TOKEN</code> injection token.</p>
<p>The injection token uniquely identifies a dependency type from the point of view of Angular, and that is how the dependency injection system knows what provider to use.</p>
<p>So now Angular knows what provider factory function to call to create the right dependency, and it goes ahead and does just that.</p>
<p>And with this, our application is now working correctly, no more errors! 😉</p>
<p>I think now you have a good understanding of how the Angular dependency injection system works, but I guess you are probably thinking:</p>
<h2 id="but-why-don-t-i-ever-have-to-configure-providers-manually">But why don't I ever have to configure providers manually?</h2>
<p>You see, even though you <em>usually</em> don't have to configure provider factory functions or injection tokens manually yourself, this is what is actually happening under the hood.</p>
<p>For every single type of dependency of your application, be it a service, a component or something else, there is <em>always</em> a provider, and there is always an injection token, or some other mechanism of uniquely identifying a dependency type.</p>
<p>This makes sense, because the constructors of your classes <em>need</em> to be called by some part of your system, and Angular always needs to know what dependency type to create, right?</p>
<p>So even when you configure your dependencies in a simplified way, there is <em>always</em> a provider under the hood.</p>
<p>To better understand this, let's progressively simplify the definition of our provider, until we reach something that you are much more used to.</p>
<h2 id="using-class-names-as-injection-tokens">Using class names as Injection Tokens</h2>
<p>One of the most interesting features of the Angular dependency injection system, is that you can use anything that is guaranteed to be unique in the Javascript runtime in order to identify a type of dependency, it doesn't have to be an explicit injection token object.</p>
<p>For example, in the Javascript runtime, class names are represented by constructor functions, and a reference to a function like for example its name is <em>guaranteed to be unique at runtime</em>.</p>
<p>A class name can then be uniquely represented at runtime by its constructor function, and because it's guaranteed to be unique, it can be used as an injection token.</p>
<p>So we can simplify a bit the definition of our provider, by taking advantage of this powerful feature:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=09.ts"></script>
<p>As we can see, we are no longer using the <code>COURSES_SERVICE_TOKEN</code> injection token object that we have manually created as a means to identify our dependency type.</p>
<p>In fact, we have removed that object from our code base altogether, because for the particular case of service classes, we can use the class name itself to identify the dependency type!</p>
<p>But if we try our program without any further modifications, we would get again the &quot;no provider&quot; error.</p>
<p>In order to make things work again, you need to use the <code>CoursesService</code> constructor function to also identify which dependencies you need:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=10.ts"></script>
<p>And with this, Angular knows what dependency to inject, and everything is working again as expected! 😉</p>
<p>So the good news is that <em>we don't need</em>, in most cases, to explicitly create an injection token.</p>
<p>Let's now see how can we further simplify our provider.</p>
<h2 id="simplified-configuration-of-providers-useclass">Simplified configuration of providers: useClass</h2>
<p>Instead of explicitly defining a provider factory function with <code>useFactory</code>, we have other ways to tell Angular how to instantiate a dependency.</p>
<p>In the case of our provider, we can use the <code>useClass</code> property.</p>
<p>This way Angular will know that the value that we are passing is a valid constructor function, that Angular can simply call using the <code>new</code> operator:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=11.ts"></script>
<p>And this already greatly simplifies our provider, as we don't need to write a provider factory function manually ourselves! 👍</p>
<p>Another super convenient feature of <code>useClass</code> is that for this type of dependencies, Angular will try to infer the injection token at runtime based on the value of the Typescript type annotations.</p>
<p>This means that with <code>useClass</code> dependencies, we don't even need the<br>
<code>Inject</code> decorator anymore, which explains why you rarely see it:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=12.ts"></script>
<p>So how does Angular know which dependency to inject?</p>
<p>Angular can determine this by inspecting the type of the injected property which is <code>CoursesService</code>, and using that type to determine a provider for that dependency.</p>
<p>As we can see, class dependencies are much more convenient to use, as opposed to having to use <code>@Inject</code> explicitly! 👍</p>
<p>For the particular case of <code>useClass</code> providers, we can simplify this even further.</p>
<p>Instead of defining a provider object manually, we can simply pass the name of the class itself as a valid provider configuration item:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=14.ts"></script>
<p>Angular will determine that this provider is a constructor function, so Angular will inspect the function, it will then create a factory function determine the necessary dependencies, and create an instance of the class on demand.</p>
<p>And this happens implicitly just based on the name of the function.</p>
<p>This is the notation that you usually use in most cases, which is super simplified and easy to use! 😉</p>
<p>With this simplified notation, you won't even be aware that there are providers and injection tokens behind the scenes.</p>
<p>But notice that just setting your provider like this won't work, because Angular will not know how to find the dependencies of this class (remember the <code>deps</code> property).</p>
<p>For this to work, you need to also apply the <code>Injectable()</code> decorator to the service class:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=15.ts"></script>
<p>This decorator will tell Angular to try to find the dependencies for this class by inspecting the types of the constructor function arguments at runtime!</p>
<p>So as you can see, this very simplified notation is how we usually use the Angular dependency injection system, without even thinking about all the nuts and bolts that are being used under the hood. 😉</p>
<p>One thing to bear in mind is that the <code>useClass</code> option will not work with interface names, <strong>it works only with class names</strong>.</p>
<p>This is because an interface is a compile-time only construct of the Typescript language, so the interface does not exist at runtime.</p>
<p>This means that an interface name, unlike a class name (via its runtime constructor function) can't be used to uniquely identify a dependency type.</p>
<p>Besides its base concepts of provider, dependencies and injection tokens, there are a few other things that are important to bear in mind about the Angular dependency injection system.</p>
<h2 id="understanding-angular-multiple-value-dependencies">Understanding Angular multiple value dependencies</h2>
<p>Most of the dependencies in our system will correspond to only one value, such as for example a class.</p>
<p>But there are some occasions where we want to have dependencies with <em>multiple different values</em>.</p>
<p>A very common example that you might have already come accross are form control value accessors.</p>
<p>These are special form directives that bind to a given form control and make the form control value available to the Forms module.</p>
<p>The problem is, there is not just one directive like this, there are many of them.</p>
<p>But it wouldn't be very practical to configure all these dependencies separately, because you usually want to access them all together at once.</p>
<p>So the solution is to have a special type of dependency that accepts multiple values, not just one, linked to the exact same dependency injection token.</p>
<p>In the particular case of form control value accessors, that special token is the <code>NG_VALUE_ACCESSOR</code> injection token.</p>
<p>For example, here is an example of a custom form control component that wants to registers itself as a control value accessor:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=16.ts"></script>
<p>Notice that we are defining here a provider for the <code>NG_VALUE_ACCESSOR</code> injection token.</p>
<p>But if we would not use the <code>multi</code> property, the existing value for this injection token would have been overwritten (more on this later).</p>
<p>But because <code>multi</code> is set to true, we are actually adding to the array of values of this dependency, instead of overwriting it.</p>
<p>Any component or directive that needs all the control value accessors, will receive them by requesting the injection of the <code>NG_VALUE_ACCESSOR</code>.</p>
<p>This will correspond to an array containing all the standard form control value accessors, plus our custom one.</p>
<h3 id="when-to-use-an-useexisting-provider">When to use an useExisting provider</h3>
<p>Notice also the use of the <code>useExisting</code> option for creating a provider.</p>
<p>This option is useful when we want to create a provider based on another existing provider.</p>
<p>In this case, we want to define a provider in a simple way just by pointing to the <code>ChooseQuantityComponent</code> class name, which can be used as a provider as we have learned.</p>
<p>This <code>useExisting</code> functionality is also useful to define an alias (an alternative name) for an existing provider.</p>
<p>Now that we have a good understanding of how providers and injection tokens work, let's talk about another fundamental aspect of the Angular dependency injection system.</p>
<h2 id="understanding-angular-hierarchical-dependency-injection">Understanding Angular Hierarchical Dependency Injection</h2>
<p>Unlike its previous AngularJs version, the Angular dependency injection system is said to be <em>hierarchical</em>.</p>
<p>So what does that mean exactly?</p>
<p>If you notice, in Angular you have multiple places available where you can define the providers for your dependencies:</p>
<ul>
<li>at the level of a module</li>
<li>at the level of a component</li>
<li>or even at the level of a directive!</li>
</ul>
<p>So what is the difference between defining a provider at all these different places, how does that work, and why are those different options even available?</p>
<p>You can define providers at multiple places because the Angular dependency injection system is <em>hierarchical</em>.</p>
<p>You see, if you need a dependency somewhere, for example if you need to inject a service into a component, Angular is going to first try to find a provider for that dependency <em>in the list of providers of that component</em>.</p>
<p>If Angular does not find a provider at the level of the component itself that needs the dependency, then Angular is going to try to find a provider <em>in the parent component</em>.</p>
<p>If it finds the provider it will instantiate and use it, but if not, it will ask <em>the parent of the parent component</em> if it has the provider that it needs, etc.</p>
<p>This process will be repeated until we reach the root component of the application.</p>
<p>If no provider is found after this process, you know what happens: yes, we get our good friend the &quot;No provider found&quot; message. 😉</p>
<p>This process of going up the component tree searching for the right provider is known as <em>dependency resolution</em>, and because it follows the hierarchical structure of our component tree, the Angular dependency system is said to be hierarchical.</p>
<p>We also need to know <em>why</em> this feature is useful.</p>
<h2 id="what-are-the-advantages-of-hierarchical-dependency-injection">What are the advantages of Hierarchical Dependency Injection?</h2>
<p>Angular is typically used to build large applications, which in some cases can become quite large.</p>
<p>One way to manage this complexity is to split up the application into many small well encapsulated modules, that are by themselves split up into a well-defined tree of components.</p>
<p>These different sections of the page will need certain services and other dependencies to work, that they might or might not want to share with other sections of the application.</p>
<p>We can imagine a well isolated section of our page that works in a completely independent way than the rest of the application, with its own local copies of a series of services and other dependencies that it needs.</p>
<p>We want to ensure that these dependencies remain private and cannot be reached by the rest of the application, to avoid bugs and other maintenance issues.</p>
<p>Some of the services that our isolated section of the application uses might be shared with other parts of the application, or with parent components that are further up in the component tree, while other dependencies are meant to be private.</p>
<p>An hierarchical dependency injection system allows us to do just that! 👍</p>
<p>With hierarchical dependency injection, we can isolate sections of the application and give them their own private dependencies not shared with the rest of the application, we can have parent components share certain dependencies with its child components only but not with the rest of the component tree, etc.</p>
<p>An hierarchical dependency injection system allows us to build our system in a much more modular way, allowing us to share dependencies between different parts of the application only when and if we need to.</p>
<p>This initial explanation is a good starting point, but to really understand how this all works, we need a complete example.</p>
<h2 id="understanding-components-hierarchical-dependency-injection-via-an-example">Understanding Components Hierarchical Dependency Injection via an example</h2>
<p>For example, let's take our <code>CoursesService</code> class. What would happen if we would try to inject this class everywhere in the Angular component tree?</p>
<p>What would happen, would we get multiple instances of the service, or only one, how does that work?</p>
<p>To help us understand this, let's give to each instance of the <code>CoursesService</code> a unique identifier, so that we can understand better what is going on:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=17.ts"></script>
<p>Now let's create a simple hierarchy of components, inject <code>CoursesService</code> in multiple places, and see what happens!</p>
<p>Let's create a root application component, that uses in its template a child<br>
<code>course-card</code> component.</p>
<p>Here is the root component <code>app.component.html</code> template:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=18.html"></script>
<p>As we can see, this component internally uses the <code>course-card</code> component inside an <code>ngFor</code> loop.</p>
<p>Here is the component class <code>app.component.ts</code> file:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=19.ts"></script>
<p>Notice that we are adding <code>CoursesService</code> to the providers of the root component, and we are also printing out to the console the unique identifier of the service instance that we get.</p>
<p>And finally, here is what the <code>course-card</code> component looks like, this is the<br>
<code>course-card.component.ts</code> file:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=20.ts"></script>
<p>Notice that we are here also adding <code>CoursesService</code> to the list of providers of the component, as well as printing out to the console the id of the service instance.</p>
<p>If we now start our application, what do you think will happen?</p>
<p>How many instances of <code>CoursesService</code> do you think will be created, and which ones get injected in which <code>course-card</code> component?</p>
<p>Here is the output of the console:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 2
course card service Id = 3
course card service Id = 4
course card service Id = 5
course card service Id = 6
course card service Id = 7
course card service Id = 8
course card service Id = 9
course card service Id = 10
course card service Id = 11
</code></pre></div>
<p>So what happened here? Let' break down what is going on.</p>
<p>So it looks like the application root component <code>app.component.ts</code> was the first to create an instance of a service, so it got Id = 1.</p>
<p>The root component checked first its own list of providers when trying to get the <code>CoursesService</code> dependency, and it found a matching provider and used it.</p>
<p>But what happened inside the <code>course-card</code> component?</p>
<p>Unlike the application root component, the <code>course-card</code> component has 10 instances created and displayed on the screen.</p>
<p>Each instance of the <code>course-card</code> component needed a <code>CoursesService</code>, so it tried to instantiate it by looking into its own list of providers.</p>
<p>Each <code>course-card</code> component instance found a matching provider in its own providers private list, and used it to create a new instance of <code>CoursesService</code> and inject in its dependencies.</p>
<p>This means that each <code>course-card</code> instance created its own separate instance of <code>CoursesService</code>, and did not need to ask the parent root component for an instance of <code>CoursesService</code>.</p>
<p>There are 10 instances of <code>course-card</code>, and each has its own private instance of <code>CoursesService</code>, which explains the log!</p>
<p>Notice that these private instances of <code>CoursesService</code> are linked to the component lifecycle of their <code>course-card</code> instance.</p>
<p>So if the component instance of <code>course-card</code> gets destroyed, their corresponding instance of <code>CoursesService</code> will also get garbage collected.</p>
<p>But the <code>CoursesService</code> is mostly a stateless class (except for our counter), so there is really no need to create so many instances of it.</p>
<p>What we would prefer, would be that there is only one instance of<br>
<code>CoursesService</code>, created by the root component, and shared with all its child components.</p>
<p>We can do so by removing the <code>CoursesService</code> provider from the providers list of the <code>CourseCardComponent</code>:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=21.ts"></script>
<p>Notice the empty list of providers for this component, we can even remove the <code>providers</code> property altogether.</p>
<p>If we do so and run our application again, here is what we get:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
</code></pre></div>
<p>As we can see, our application now only has one instance of <code>CoursesService</code>, as intended. 👍</p>
<p>So we now understand how hierarchical dependency injection works <em>in terms of the component tree</em> only - Angular search for a provider match in the component first, and then scans all its parent components.</p>
<p>But what about modules? Those can also have their own providers, right?</p>
<h2 id="understanding-modules-hierarchical-dependency-injection-via-an-example">Understanding Modules Hierarchical Dependency Injection via an example</h2>
<p>Let's leave our components as they are currently, meaning:</p>
<ul>
<li>the app root component has a <code>CoursesService</code> provider</li>
<li>the <code>course-card</code> component does not have its own private providers</li>
</ul>
<p>Notice that the <code>course-card</code> component is part of a <code>CoursesModule</code>.</p>
<p>So what happens if we keep the component providers as they are, and now add two more providers at the module level?</p>
<p>First let's add a provider at the level of <code>CoursesModule</code>:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=22.ts"></script>
<p>This is a feature module which is part of the application root module.</p>
<p>Let's now also add another provider at the level of the root module itself:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=23.ts"></script>
<p>So we now have two extra providers in our application, and a total of 3 providers:</p>
<ul>
<li>1 provider at the level of the root component <code>AppComponent</code></li>
<li>1 provider at the level of the feature module <code>CoursesModule</code></li>
<li>1 provider at the level of application root module <code>AppModule</code></li>
</ul>
<p>If we now run our application, what do you think will happen?</p>
<p>Here is the console output:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
</code></pre></div>
<p>It's the exact same output!</p>
<p>So what is going on here?</p>
<h2 id="modules-vs-components-dependency-injection-hierarchies">Modules vs Components Dependency Injection Hierarchies</h2>
<p>What is actually happening is that there are two separate dependency injection hierarchies:</p>
<ul>
<li>there is an hierarchy at the level of the components, that follows the tree structure of the components on the page</li>
<li>But there is also a separate injection hierarchy at the level of the modules</li>
</ul>
<p>And the hierarchy at the level of the components takes precedence over the module injection hierarchy! 😉</p>
<p>So when Angular is trying to find a dependency for a component or service, it will first try to create the dependency by using providers at the level of the component tree, if available.</p>
<p>If Angular follows all the components up until the root component without finding a matching provider and it still doesn't find anything, only then will Angular try to find a matching provider at the level of the modules hierarchy.</p>
<p>Angular will then start with the providers of the current module, and look for a matching provider.</p>
<p>If it doesn't find it, then Angular will try to find a provider with the parent module of the current module, etc. until reaching the root module of the application.</p>
<p>This system composed of two separate injection hierarchies allows us to modularize our application into two separate dimensions:</p>
<ul>
<li>
<p>we can modularize our application by making certain dependencies available in a given section of the component tree by using the component injection hierarchy</p>
</li>
<li>
<p>but we can also modularize and create separate versions of a service that are used only by certain modules of our application by using the modules injection hierarchy</p>
</li>
</ul>
<p>Now that we are familiar with the main concepts of how the hierarchical dependency injection system works, let's now learn how to further configure its dependency resolution mechanism.</p>
<h2 id="configuring-the-dependency-injection-resolution-mechanism">Configuring the Dependency Injection Resolution mechanism</h2>
<p>As we have learned, the Angular <em>component</em> dependency injection resolution mechanism always starts at the current component, and scans for matching providers all the way up the root component of the application, and it doesn't find a matching dependency it throws an error.</p>
<p>But what if we want to tweak this behavior a little bit?</p>
<h3 id="understanding-the-optional-decorator">Understanding the <code>@Optional</code> decorator</h3>
<p>For example, what if we would want to prevent the final error from being thrown, because the dependency might not be needed and you might have another alternative to using it?</p>
<p>We can mark a dependency as optional by using the <code>@Optional</code> decorator:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=27.ts"></script>
<p>This will prevent an error from being thrown if no matching provider is found for the dependency, but you need to make sure that your component checks if the dependency exists or not and provide an alternative to it if it doesn't.</p>
<h3 id="understanding-the-skipself-decorator">Understanding the <code>@SkipSelf</code> decorator</h3>
<p>You can also tweak a bit the place where the dependency resolution mechanism <em>starts</em> looking for a matching provider.</p>
<p>For example, you might have some provider for a service at the level of your component that you want to provide to its child components, but the component itself needs an instance of that same service to work, and it needs to get it from its parent components and not from its own providers.</p>
<p>Admittedly, this must be a very rare case. 😃</p>
<p>But if you ever run into it, you can skip your local component providers and start the matching process <em>directly at the parent component</em> and from there down to the root component by using the <code>SkipSelf</code> decorator:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=28.ts"></script>
<p>In our application, this will result in the local <code>CoursesService</code> provider to be skipped, meaning that that provider would only be visible to child components of the <code>course-card</code> component.</p>
<p>If we run our application, this is the log that we would get:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
course card service Id = 1
</code></pre></div>
<p>As we can see, the provider at the level of <code>CourseCardComponent</code> was skipped, and provider at the level of the <code>CoursesModule</code> was used.</p>
<h3 id="understanding-the-self-decorator">Understanding the <code>@Self</code> decorator</h3>
<p>Besides configuring where we start the match process for our dependencies, we can also tweak a bit where that matching process ends.</p>
<p>For example, if we want our component to look for a dependency in its own providers only, and skip checking the providers of all its parent components, we can do so by using the <code>Self</code> decorator:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=29.ts"></script>
<p>This time around, the local provider for <code>CoursesService</code> is going to be taken, and the parent instance at the level of the <code>CoursesModule</code> is going to be skipped.</p>
<p>Here is what our application log would look like in this case:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 2
course card service Id = 3
course card service Id = 4
course card service Id = 5
course card service Id = 6
course card service Id = 7
course card service Id = 8
course card service Id = 9
course card service Id = 10
course card service Id = 11
</code></pre></div>
<p>As we can see, we fall again into the scenario where every instance of our component has its own private instance of a service.</p>
<h3 id="understanding-the-host-decorator">Understanding the <code>@Host</code> decorator</h3>
<p>So far we have been talking about components and how they interact with the dependency injection system, but what about directives?</p>
<p>Because components are just a special type of directive, all that we have learned so far for components also applies to directives.</p>
<p>But there is one special case: imagine that the component has a private instance of a service, created by its own provider.</p>
<p>Now that component might or might not have a directive applied to it, that is part of the same module and that directive is designed so that it interacts closely with that particular component.</p>
<p>Because that directive is closely coupled with the component, it might want to access some of the private services associated to that component, and no other.</p>
<p>Imagine a simple <code>HighlightedDirective</code>, that is meant to visually highlight a course card to which it's applied.</p>
<p>Let's say that this directive is designed to interact tightly with the<br>
<code>CourseCardComponent</code>, and would like to access its private instance of<br>
<code>CoursesService</code>.</p>
<p>The directive could access the private component service in the following way:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=30.ts"></script>
<p>The use of the <code>Host</code> decorator configures where Angular should <em>stop</em> searching for a dependency, in a similar way to what <code>Self</code> does.</p>
<p>But in this case, this decorator is meant for directives only, and it says to Angular to search for a matching provider only on the providers of its host component, and nowhere else.</p>
<p>Let's now apply this directive to each <code>course-card</code> component in our application:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=31.html"></script>
<p>Notice the use of the <code>highlighted</code> attribute, that assigns a companion instance of the <code>HighlightedDirective</code> to each instance of <code>CourseCardComponent</code>.</p>
<p>If we now run our application, we get the following console output:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">App component service Id = 1
course card service Id = 2
coursesService highlighted 2
course card service Id = 3
coursesService highlighted 3
course card service Id = 4
coursesService highlighted 4
course card service Id = 5
coursesService highlighted 5
course card service Id = 6
coursesService highlighted 6
course card service Id = 7
coursesService highlighted 7
course card service Id = 8
coursesService highlighted 8
course card service Id = 9
coursesService highlighted 9
course card service Id = 10
coursesService highlighted 10
course card service Id = 11
coursesService highlighted 11
</code></pre></div>
<p>As we can see, every instance of the <code>HighlightedDirective</code> gets access to the private instance of the companion <code>CoursesService</code> to which the directive is applied.</p>
<p>And with this, we have now fully covered the multiple ways that we have available to configure the Angular dependency resolution mechanism.</p>
<p>Now that we understand well how the hierarchical dependency injection works, let's talk about another of the many powerful features of the Angular dependency injection system.</p>
<h2 id="what-are-tree-shakeable-providers">What are Tree-Shakeable Providers?</h2>
<p>The providers that we have been using so far as examples are missing one important property: they are not tree shakeable.</p>
<p>So what does this mean?</p>
<p>So far, the providers that we have been defining were all added explicitly to the list of providers of either a component or module, using the <code>providers</code> property.</p>
<p>This approach has a practical problem though.</p>
<p>Imagine that an application has a dependency on a module that by its turn imports another module which then provides a service class.</p>
<p>Now imagine that this imported service class is effectively not used anywhere in our application, by whatever reason!</p>
<p>And this is actually a very common scenario.</p>
<p>If you are using for example AngularFire or other large third-party modules with tons of functionality, these modules contain all sorts of services that you might need in your application, <em>or not</em>.</p>
<p>You might use some of the services, but probably not all of them.</p>
<p>The idea is that we should be able to import a module, but if don't use some of its services then we shouldn't need to include them in our production bundle.</p>
<p>So how can this be achieved?</p>
<h3 id="what-is-tree-shaking">What is tree shaking?</h3>
<p>When the Angular CLI is building our application bundle, it will try as much as possible to &quot;tree shake&quot; any code that is not necessary out of the bundle, in order to reduce its size as much as possible.</p>
<p>The CLI will try to do by statically inspecting the Typescript dependencies of our code, and determine if a dependency is being used or not.</p>
<p>If it finds that the dependency is not being used, it will remove it from the bundle and so reduce its size.</p>
<p>But if we are adding the module with the unused services directly in the providers property of a module or component, we need to first import that module or service directly via a Typescript import.</p>
<p>And this Typescript import will effectivelly <em>prevent</em> the tree shaking service from removing the unused service.</p>
<p>The tree shaker sees that the service is being imported explicitly via a Typescript import, and so it will wrongly think its being used and it won't remove it from the production bundle.</p>
<p>So how do we solve this?</p>
<p>Well, we need tree-shakeable providers. 😉</p>
<h2 id="understanding-tree-shakeable-providers-via-an-example">Understanding Tree-Shakeable Providers via an example</h2>
<p>What we want to do is to define the <code>CoursesService</code> as part of the <code>CoursesModule</code>, which is a feature module.</p>
<p>This could perfectly be a third-party module that we imported in our application as well.</p>
<p>We want to define a provider for the <code>CoursesService</code> in a way that, if it gets used by whoever imports the <code>CoursesModule</code>, it will be included in the final bundle.</p>
<p>But if by some reason an application imports the <code>CoursesModule</code> and ends up never using the <code>CoursesService</code>, then the service should <em>not</em> get included in the bundle.</p>
<p>In order to do this, the first thing that we do is to <em>remove</em> the <code>CoursesService</code> from the list of providers of the <code>CoursesModule</code>:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=24.ts"></script>
<p>But now, won't we get the &quot;provider not found&quot; error message?</p>
<p>Yes, because there is no provider defined yet. 😉</p>
<p>Here is how we can define a provider for <code>CoursesService</code> at the level of the<br>
<code>CoursesModule</code>, <em>without</em> importing it in the <code>courses.module.ts</code> file:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=25.ts"></script>
<p>As you can see, we flipped the order of dependencies, we have imported the<br>
<code>CoursesModule</code> inside the <code>CoursesService</code> and not vice-versa, and defined the module-level provider in the service class itself, using the <code>Injectable</code> decorator.</p>
<p>This way, <code>CoursesModule</code> does not import the service class at all, and so if the service is not used, it will be tree-shaked out of the production bundle as expected.</p>
<p>Notice that the <code>Injectable</code> decorator allows us to define providers in all sorts of ways, and not only module-level providers.</p>
<p>We have also access to the options <code>useClass</code>, <code>useValue</code>, <code>useExisting</code>, and <code>deps</code> that we have access when configuring a provider at the level of a module or component.</p>
<p>Using <code>providedIn</code>, we can not only define module-level providers, but we can even provide service to <em>other modules</em>, by making the services available at the root of the module dependency injection tree:</p>
<script src="https://gist.github.com/jhades/a17be59e153a01e9f65869caa5a80e12.js?file=26.ts"></script>
<p>This is the most common syntax that you are probably already familiar with.</p>
<p>With this syntax, the <code>CoursesService</code> is now an application-wide singleton, meaning that there is only instance of the service for the whole application, which makes sense in our case because our service is stateless.</p>
<p>And with this, we have reached the end of this section, let's now quickly summarize the key takeaways that we have learned throughout this post.</p>
<h2 id="summary">Summary</h2>
<p>As we have learned, there is a lot going on behind the scenes with the Angular dependency injection system. 😉</p>
<p>The dependency system is very flexible, and it has a ton of powerful configuration options.</p>
<p>And yet, its mostly commonly used syntax of simply just dropping a class name into a list of providers is super easy to use!</p>
<p>Knowing how the dependency injection system works in detail will however prove to be very useful when you are designing your application in the most modular way possible.</p>
<p>The dependency injection system, because it's hierarchical and because it contains two separate injection hierarchies (components and modules), allows you to define in a very fine-grained way which dependencies are visible in which parts of the application, and which dependencies are hidden.</p>
<p>These features are very useful especially if you creating a third-party module and you want to ship services that might be used in a ton of different applications, but also if you are modularizing a large application.</p>
<p>Although all these powerful features are available, most of the time the default configuration mechanism <em>just works</em> and is super easy to use. 😃</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about many other powerful Angular core features, I recommend checking the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive</a> course, where dependency injection and many other features are covered in great detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular ngIf: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-ngif/</link>
      <guid isPermaLink="false">604887e8b527c70039a64111</guid>
      <pubDate>Thu, 11 Mar 2021 14:10:52 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>Learn all the features available in ngIf, learn the best way to use it to consume Observables, avoid a common anti-pattern.</description>
      <content:encoded><![CDATA[<p>In this post, we are going to cover <em>all</em> the features that we have available for using the Angular <code>ngIf</code> core directive.</p>
<p>Besides the most commonly used features, we are going to learn how to avoid a <strong>potential <code>ngIf</code> anti-pattern</strong> that we might run into while developing more complex UI screens that consume a lot of Observable data coming from different sources (backend, Observable services, stores, etc.).</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>What is Angular ngIf?</li>
<li>How does ngIf compare to hiding elements using CSS?</li>
<li>What type of expressions can ngIf accept?</li>
<li>The ngIf else syntax</li>
<li>The ngIf if then else syntax</li>
<li>Consuming observable data with ngIf and the async pipe</li>
<li>A potential anti-pattern while consuming Observable data with ngIf</li>
<li>The Single Data Observable pattern</li>
<li>How does ngIf work under the hood?</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Core features, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-core/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know about Angular <code>ngIf</code>!</p>
<p><strong>Note:</strong> If instead of <code>ngIf</code> you are looking for the <code>@if</code> syntax, then check my other guide instead: <a href="https://blog.angular-university.io/angular-if/">Angular @if: Complete Guide</a></p>
<h2 id="what-is-angular-ngif">What is Angular ngIf?</h2>
<p>Even though HTML is also a programming language in its own right, it does not have an <strong>if</strong> statement, unlike for example Javascript.</p>
<blockquote>
<p>The Angular <code>ngIf</code> directive works essentially as an if statement for HTML, adding this missing feature to the language under the form of the special <code>ngIf</code> attribute.</p>
</blockquote>
<p>We need to pass a condition to <code>ngIf</code>, in order for it to work. Here are a couple of examples:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=01.html"></script>
<p>In this example, the container div will only be shown to the user if the user is logged in, otherwise the whole content of the div is not visible.</p>
<p>Inside the container div, there is a button only visible if the user is an administrator.</p>
<h4 id="what-if-i-don-t-have-anywhere-convenient-to-apply-ngif">What if I don't have anywhere convenient to apply ngIf?</h4>
<p>In the case of container elements, if there is no container available for the section that we want to show or hide, then we <em>don't</em> have to create a container div just to be able to apply <code>ngIf</code>.</p>
<p>Instead, we can apply <code>ngIf</code> on top of the <code>ng-container</code> directive. This will show or hide the content of <code>ng-container</code>, without having to create an extra div just for that:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=02.html"></script>
<h2 id="how-does-ngif-compare-to-hiding-elements-using-css">How does ngIf compare to hiding elements using CSS?</h2>
<p>Even though HTML does not have a built-in if statement, there are ways of hiding portions of the page with just plain CSS, by using the <code>display</code> and<br>
<code>visibility</code> attributes.</p>
<p>We can easily add or remove these CSS attributes to an HTML element using Javascript and hide an element from the page. But that is <em>not</em> the same as using <code>ngIf</code>.</p>
<p>With <code>ngIf</code>, if an element is hidden then that element does not exist <em>at all</em> in the page.</p>
<p>Meaning that if you inspect the page using for example the Chrome Dev Tools, you <em>won't</em> find any HTML element present in the DOM.</p>
<p>Instead of it, you will find a strange-looking HTML comment similar to this one, where the <code>ngIf</code> directive was applied:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">&lt;!--bindings={
  &quot;ng-reflect-ng-if&quot;: &quot;false&quot;
}--&gt;
</code></pre></div>
<blockquote>
<p>This comment is there just for debugging purposes, to help identify where the missing element should have been placed in case it was visible.</p>
</blockquote>
<p>This is very different than the behavior of the <code>display</code> or <code>visibility</code> CSS properties. For example, if we set the <code>display</code> property to the value <code>none</code>, the HTML element will be hidden.</p>
<p>But if we inspect the page with the Dev Tools, we will see that DOM elements are still there present on the page, it's just that they are not visible:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/angular-ngif/angular-ng-if-vs-css-2.png" alt="Angular ngIf compared to CSS display and visibility properties" loading="lazy" decoding="async"></p>
<p>With the CSS <code>visibility</code> attribute set to <code>hidden</code>, something very similar would occur. The HTML element would be hidden from the user, but still present on the page upon inspection with the Dev Tools.</p>
<p>With hidden visibility, the element will still occupy some blank space on the page, even though the element is hidden. This is unlike the use of <code>display:none</code>, where no space on the page is occupied.</p>
<p>But in both cases, with CSS the elements are still present in the DOM, consuming resources however small, unlike with <code>ngIf</code> where hidden elements simply don't exist.</p>
<blockquote>
<p>In general, while building Angular applications, we should always prefer to hide elements using <code>ngIf</code> instead of using plain CSS.</p>
</blockquote>
<h2 id="what-type-of-expressions-can-ngif-accept">What type of expressions can ngIf accept?</h2>
<p>The <code>ngIf</code> directive can take as input any valid Typescript expression and not just a boolean. The thruthiness of the expression is then going to get evaluated, to determine if the element should be shown or not.</p>
<p>Besides booleans we can also pass to <code>ngIf</code> for example strings, arrays, objects, etc. Here are a few examples of what would happen if we passed other primitive types to <code>ngIf</code>:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=03.html"></script>
<p>And here are some more examples of passing arrays and objects to <code>ngIf</code>:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=04.html"></script>
<p>As we can see, all that it matters to determine if an element is shown or not is the <em>truthiness</em> of the expression passed to <code>ngIf</code>.</p>
<h2 id="the-ngif-else-syntax">The ngIf else syntax</h2>
<p>If we could use an &quot;if&quot; syntax in HTML, we will also need an <em>else</em> clause, just like in Javascript we have the if-else statement.</p>
<p>In Angular, we can use the <code>ngIf</code> else syntax, in the following way:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=05.html"></script>
<p>Besides the <code>courses.length</code> expression, we can also pass to <code>ngIf</code> an else clause, that points to a template reference (the <code>noCourses</code> template in this case).</p>
<p>If the expression is falsy, the <code>noCourses</code> template will be instantiated and applied to the page, right where the <code>ngIf</code> directive was applied.</p>
<p>Otherwise, if the expression <code>courses.length</code> remains truthy, then the <code>noCourses</code> template will never be instantiated, and won't be present at all on the page.</p>
<h2 id="the-ngif-then-else-syntax">The ngIf then else syntax</h2>
<p>The Angular <code>ngIf</code> directive also supports a if-then-else syntax, just like we have available in Javascript. Here is an example:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=06.html"></script>
<p>In this example, we have applied <code>ngIf</code> to an <code>ng-container</code> directive. Either one of the two templates <code>coursesList</code> or <code>noCourses</code> is going to be instantiated, depending on the truthiness of the <code>courses.length</code> expression.</p>
<p>Unlike Javascript, this syntax does not support multiple &quot;else if&quot; clauses, but you can implement equivalent functionality using <code>ngSwitch</code>.</p>
<h2 id="consuming-observable-data-with-ngif-and-the-async-pipe">Consuming observable data with ngIf and the async pipe</h2>
<p>If you are building applications in reactive style, then <code>ngIf</code> is usually used to feed the observable data to the template.</p>
<p>The <code>ngIf</code> directive can be combined with the <code>async</code> pipe in order to consume an Observable in the following way:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=07.html"></script>
<p>In this example, <code>courses$</code> is an Observable emitting as values arrays of course objects. This Observable could have been fetched from memory, or from an in-memory store.</p>
<p>Independently of the origin of the data, the <code>async</code> pipe will subscribe to the Observable, and make the values emitted by it available to the template.</p>
<p>In order to apply the <code>async</code> pipe, we use the <code>ngIf</code> syntax with the &quot;as&quot; syntax. The values emitted by the Observable are going to be available inside the scope of the <code>ngIf</code> directive via the <code>courses</code> local template variable.</p>
<p>One of the advantages of consuming Observables with the async pipe directly in the template is that the pipe will take care of unsubscribing from the Observable automatically when the component gets destroyed.</p>
<p>Another advantage of consuming data this way is that the component view will get automatically updated with the latest Observable data if using OnPush change detection.</p>
<h2 id="a-potential-anti-pattern-while-consuming-observables-with-ngif">A potential anti-pattern while consuming Observables with ngIf</h2>
<p>Using this combination of <code>ngIf</code> and the <code>async</code> pipe to consume Observable data is very convenient, but this can be easily misused in more complex user interfaces, where multiple sources of Observable data need to be displayed in different sections of the page.</p>
<p>You might have come across some components with templates that look a lot like this:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=08.html"></script>
<p>This page is made up of three different peer sections, at the same level of the HTML tree:</p>
<ul>
<li>the header only needs the user</li>
<li>the body needs all data: courses, the lessons, and the user</li>
<li>the footer only needs the courses and the lessons</li>
</ul>
<p>In order to consume the Observable data, we had to resort to repeating the use of <code>ngIf</code> and the <code>async</code> pipe, at multiple levels of the page.</p>
<p>We also used nested <code>ng-container</code> directives in both the body and the footer, just to be able to access multiple Observables in one section of the page.</p>
<p>In the case of the body, we even had to resort to 3 levels of nesting, and we have seen components with sometimes 5 or 6 levels of nesting, just to consume Observable data.</p>
<h3 id="when-does-this-overuse-of-ngif-async-occur">When does this overuse of ngIf/async occur?</h3>
<p>This will only happen in more complex components, where the data of each Observable is used a little bit everywhere on the page, and not just in one well-contained section.</p>
<p>Also, the component might begin simple, with each Observable only being used in a certain part of the page, but over time new requirements show up that cause the observable data to be used in new places of the page, and then the nested <code>ng-container</code> directives start to multiply.</p>
<p>Notice that nesting <code>ng-container</code> by itself is not problematic, and is normal when we have multiple structural directives like <code>ngIf</code>, <code>ngFor</code>, etc. in one section of the page, as we can only apply one structural directive per element.</p>
<p>What we are talking about here, is the repeated use of this <code>ngIf</code> and <code>async</code> pipe combination, <em>just for the purpose</em> of accessing data, and nothing more.</p>
<h3 id="does-this-cause-any-problems-in-practice">Does this cause any problems in practice?</h3>
<p>Not only does this code repetition and nesting not look right visually, this makes the component harder to read and maintain over time.</p>
<p>You might think of splitting the component into many different subcomponents to try to alleviate this. The problem is that the different sections of the page might make much more sense to be put on the same component because they are tightly related to each other.</p>
<h3 id="how-is-this-commonly-solved">How is this commonly solved?</h3>
<p>A common attempt to solve this problem is to try to get all the data needed at once, at the top of the component, like so:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=09.html"></script>
<p>Here we have nested the <code>ngIf</code> directives at the top of the component template so that we get all the data needed anywhere in the component upfront.</p>
<p>All this nesting doesn't look great visually, but at least it prevents a lot of the code repetition. If it works, why not? The problem is, this doesn't work very well in practice in terms of user experience.</p>
<h3 id="why-doesn-t-this-upfront-nesting-solution-work-great-in-practice">Why doesn't this upfront nesting solution work great in practice?</h3>
<p>Usually, we want to show to the user something on the screen as early as possible, and some of these data sources might take longer to fetch the data than others.</p>
<p>For example, imagine that the <code>user$</code> data comes from an existing in-memory store, and is immediately available.</p>
<p>But the <code>courses$</code> data, on the other hand, is coming from a REST API call which is very fast, while the <code>lessons$</code> data comes from another API call, that takes longer.</p>
<p>Ideally, we want to show the <code>user$</code> data immediately as it's already available in memory, then we can show the courses data once it arrives, and then finally display also the lessons data.</p>
<p>The problem is, all this <code>ngIf</code> nesting would <em>prevent</em> that! With the current solution based on nesting <code>ngIf</code> 3 times, the component is only going to be displayed to the user when <em>all</em> the data is ready.</p>
<p>So as we can see, this solution is not only visually unappealing, there can also be practical consequences in terms of user experience.</p>
<p>So how can we improve on this, is there an alternative way?</p>
<h2 id="the-single-data-observable-pattern">The Single Data Observable pattern</h2>
<p>For simpler screens, the issues that we have discussed above are probably not a huge problem.</p>
<p>But if your screen starts growing in complexity, and you start to feel that all this <code>ngIf</code>/<code>async</code> nesting is starting to cause maintainability issues and user experience problems, you might want to refactor your component into the single data observable pattern.</p>
<p>With this pattern, here is what the template of the component will look like:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=10.html"></script>
<p>As you can see, there is no more nesting involved, and no more multiple uses of the <code>ngIf</code>/<code>async</code> combination. We access all the data that the template needs in one go at the top of the component, via a <code>data$</code> Observable, so we only apply the <code>async</code> pipe once.</p>
<p>This Observable contains all the data that the component template will need throughout its lifecycle, which explains the name of the pattern.</p>
<h3 id="how-does-this-pattern-help-with-the-previous-problems">How does this pattern help with the previous problems?</h3>
<p>Besides avoiding the unnecessary nesting and making the template much easier to read and reason about, this pattern also helps with the UI issues that we mentioned before.</p>
<p>Actually, you can build this <code>data$</code> Observable to behave in any way that you need to provide the best user experience.</p>
<p>For example, if the <code>user$</code> data is already available, you can have this Observable immediately emit a value with the user property filled in, and the other properties with default values:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=11.ts"></script>
<p>This would allow the <code>user$</code> data to be displayed, while the rest of the data is still being fetched. Once the courses API call ends, we can then emit a second value for the <code>data$</code> Observable containing the courses:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=12.ts"></script>
<p>This would allow us to display even more data to the user, maybe even already hiding the global loading indicator, and leaving only a more local loading indicator still spinning.</p>
<p>Later, when the lessons arrive from the backend, we can emit one final value of the <code>data$</code> Observable, containing all the data:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=14.ts"></script>
<h3 id="how-to-create-the-single-data-observable">How to create the Single Data Observable?</h3>
<p>The <code>data$</code> Observable can be built with any combination of RxJs operators that you need, in order to meet the exact needs of the UI.</p>
<p>But most commonly, the best way to build this Observable is to use RxJs <a href="https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest" target="_blank" rel="noopener">combineLatest</a>. Here is an example of how to build the <code>data$</code> Observable:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=15.ts"></script>
<p>Let's break down what is going on here, step by step. To start, we are creating three separate Observables (<code>user$</code>, <code>courses$</code> and <code>lessons$</code>).</p>
<p>The first <code>user$</code> Observable comes from an in-memory store, and does not emit a default value. This makes sense, given that there is no default user profile.</p>
<p>But the two other Observables, coming from backend services, do have logical default values (the empty array), defined via the <code>startWith</code> operator.</p>
<p>This means that each of those Observables will emit first the empty array <code>[]</code>, and only later they will emit the result of the backend call.</p>
<p>Finally, we have combined all 3 observables using <code>combineLatest</code>, which will create a result Observable, that emits tuple values.</p>
<p>These tuples contain the values emitted by each of the composing Observables in order, meaning <code>[user, courses, lessons]</code>. We then transform this tuple into an object of type <code>ExampleData</code>, using the map operator.</p>
<p>And with this, using just a couple of very commonly used RxJs operators, we have built exactly the <code>data$</code> Observable that we need, and now our template is a lot simpler and maintainable, at a small expense of a bit of extra code.</p>
<h3 id="in-case-you-are-not-familiar-with-combinelatest">In case you are not familiar with combineLatest</h3>
<p>If you use this pattern in your applications, notice an important property of<br>
<code>combineLatest</code>: it will not emit its first tuple until its composing Observables <em>all</em> emit their first value.</p>
<p>This is why adding default values to <code>courses$</code> and <code>lessons$</code> is important, otherwise, we wouldn't be able to feed to the template the user and courses data immediately as it becomes available.</p>
<p>The <code>data$</code> Observable that we have defined will wait for a user to be emitted, and after that, it will continue to emit values whenever any of the <code>user$</code>,<br>
<code>courses$</code> and <code>lessons$</code> Observables emit themselves values.</p>
<p>After <code>combineLatest</code> emits its first tuple value, then any new values emitted by<br>
<code>user$</code>, <code>courses$</code> or <code>lessons$</code> will result in the emission of a new result tuple.</p>
<h4 id="when-is-it-worth-to-use-the-single-data-observable-pattern">When is it worth to use the Single Data Observable pattern?</h4>
<p>It's probably not worth it to use the single data observable pattern systematically, but only in screens that consume several observable sources, where its hard to tell upfront exactly where in the page the multiple observables are going to be needed over time.</p>
<p>If the screen is going to be complex and accept multiple observables, we might as well use it from the beginning. But if not, its very simple to refactor into this pattern later.</p>
<p>If you are building your UI in reactive style, this pattern will make your larger and more complex components a lot easier to maintain.</p>
<p>On the other hand, this pattern is overkill for simpler screens, so its use is better decided on a case-by-case basis.</p>
<h2 id="how-does-ngif-work-under-the-hood">How does ngIf work under the hood?</h2>
<p>To wrap up our deep dive into the <code>ngIf</code> directive, let's talk a bit about the strange <code>*</code> syntax applied to <code>*ngIf</code>, and what it means.</p>
<p>The <code>*</code> syntax means that <code>ngIf</code> is a structural directive, meaning that it affects the structure of the page.</p>
<p>When Angular sees the <code>*</code>, the template compiler is going to take the template in its initial form:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=16.html"></script>
<p>And Angular is going to de-sugar the <code>*ngIf</code> syntax into the following form:</p>
<script src="https://gist.github.com/jhades/712379a271bd9694a1500bedfbdc41c4.js?file=17.html"></script>
<p>As we can see, under the hood the <code>*ngIf</code> directive is simply a plain Angular attribute that targets the property <code>ngIf</code>.</p>
<p>The <code>*</code> syntax simply means that the content of the element where the directive is applied is considered an <code>ng-template</code>, that might or might not be included in the page depending if the structural directive applied to it decides to instantiate the template or not.</p>
<p>Notice that this under the hood de-sugaring process happens with all structural directives (like <code>*ngFor</code>, etc.), and not only with <code>ngIf</code>.</p>
<h2 id="summary">Summary</h2>
<p>As we have learned, the <code>ngIf</code> directive works just like the missing if-then-else feature of the HTML language!</p>
<p>Using it, we can easily add or remove elements from the page, depending on the truthiness of a Javascript expression.</p>
<p>When an element gets removed from the page using <code>ngIf</code>, it gets removed <em>completely</em>, its not like the element is hidden using CSS.</p>
<p>If you adopt a reactive style for your applications, <code>ngIf</code> is often used in combination with the <code>async</code> pipe, to consume observable data.</p>
<p>For components with a lot of data sources, this might lead to lots of <code>ngIf</code> nesting and code repetition in the template just to access the data, as well as page startup UI issues.</p>
<p>If you run into these issues, consider refactoring your component into using the single data observable pattern, where only one data observable is fed to the view.</p>
<p>This will greatly simplify the template and improve the component startup experience. The example given with <code>combineLatest</code> is a common one, but feel free to add any other combination of operators in order to get exactly the data observable that the view needs.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about all the available Angular Core directives, we recommend checking the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive</a> course.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular FormArray: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-form-array/</link>
      <guid isPermaLink="false">603f63220aa427003961a6e2</guid>
      <pubDate>Wed, 03 Mar 2021 14:45:57 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Forms</category>
      <description>Learn how to build dynamic Angular Forms with FormArray by adding or removing form controls at runtime. Build an in-place editable data table.</description>
      <content:encoded><![CDATA[<p>In this post, you are going to learn everything that you need to know about the Angular <code>FormArray</code> construct, available in Angular Reactive Forms.</p>
<p>We are going to learn exactly what is an Angular <code>FormArray</code>, what is the difference towards a normal <code>FormGroup</code>, when to use it and why.</p>
<p>We are going to give an example of a common use case that would be hard to implement without a <code>FormArray</code>: an <strong>in-place editable table</strong> with multiple form controls per line, where new editable rows can be added or removed on demand by the user.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>What is an Angular <code>FormArray</code>?</li>
<li>What is the difference between a <code>FormArray</code> and a <code>FormGroup</code>?</li>
<li>The <code>FormArray</code> API</li>
<li>Creating an in-place editable table using <code>FormArray</code></li>
<li>The <code>formArrayName</code> directive</li>
<li>When to use an Angular <code>FormArray</code> vs a <code>FormGroup</code>?</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Forms, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-forms/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know about Angular <code>FormArray</code>!</p>
<h1 id="what-is-an-angular-formarray">What is an Angular FormArray?</h1>
<p>In Angular Reactive Forms, every form has a form model defined programmatically using the <code>FormControl</code> and <code>FormGroup</code> APIs, or alternatively using the more concise <code>FormBuilder</code> API, which we will be using throughout this guide.</p>
<p>In most cases, all the form fields of a form are well known upfront, and so we can define a static model for a form using a <code>FormGroup</code>:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=01.ts"></script>
<p>As we can see, using a <code>FormGroup</code>, we can define a group of related form controls, their initial values, and form validation rules, and give property names for each field of the form.</p>
<p>This is possible because this is a static form with a pre-defined number of fields that are <em>all known upfront</em>, which is the most common case when it comes to forms.</p>
<p>But what about other more advanced but still frequently encountered situations where the form is much more dynamic, and where not all form fields are known upfront (if any)?</p>
<p>Imagine a dynamic form where form controls are added or removed to the form by the user, depending on its interaction with the UI.</p>
<p>An example would be a form that is fully dynamically built according to data coming from the backend!</p>
<p>Another more common example of a dynamic form would be an <strong>in-place editable table</strong>, where the user can add or remove lines containing multiple editable form controls:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/angular-form-array/angular-form-array-example.png" alt="Angular Form Array Example - an in-place editable table" loading="lazy" decoding="async"></p>
<p>In this dynamic form, the user can add or remove new controls to the form by using the Add and Delete buttons.</p>
<p>Each time that the user clicks on the Add button, a new lesson row will be added to the form containing two new form controls.</p>
<p>We will be implementing this example in this guide using <code>FormArray</code>. But the main question is: why can't this form be implemented using <code>FormGroup</code>?</p>
<h1 id="what-is-the-difference-between-a-formarray-and-a-formgroup">What is the difference between a FormArray and a FormGroup?</h1>
<p>Unlike our initial example where we defined the form model using <code>FormGroup</code> via a call to the <code>fb.group()</code> API, in the case of an in-place editable table, we don't know the number of form controls upfront.</p>
<p>And this is because we can't know upfront the number of rows that the table will have. The user might add an unknown number of rows using the add button, and he might even remove them midway through by using the delete lesson button.</p>
<p>We wouldn't be able to define a form model using <code>FormGroup</code>, without knowing the exact number of rows. Also, it would be hard to give to the fields pre-defined names.</p>
<p>But we can define a form model for this in-place editable table using a<br>
<code>FormArray</code> instead.</p>
<p>A <code>FormArray</code>, just like a <code>FormGroup</code>, is also a form control container, that aggregates the values and validity state of its child components.</p>
<p>But unlike a <code>FormGroup</code>, a <code>FormArray</code> container does not require us to know all the controls up front, as well as their names.</p>
<p>Actually, a <code>FormArray</code> can have an undetermined number of form controls, starting at zero! The controls can then be dynamically added and removed depending on how the user interacts with the UI.</p>
<p>Each control will then have a numeric position in the form controls array, instead of a unique name.</p>
<p>Form controls can be added or removed from the form model anytime at runtime using the <code>FormArray</code> API.</p>
<h1 id="the-formarray-api">The FormArray API</h1>
<p>These are the most commonly used methods available in the <code>FormArray</code> API:</p>
<ul>
<li><strong>controls:</strong> This is an array containing all the controls that are part of the array</li>
<li><strong>length:</strong> This is the total length of the array</li>
<li><strong>at(index):</strong> Returns the form control at a given array position</li>
<li><strong>push(control):</strong> Adds a new control to the end of the array</li>
<li><strong>removeAt(index):</strong> Removes a control at a given position of the array</li>
<li><strong>getRawValue():</strong> Gets the values of all form controls, via the <code>control.value</code> property of each control</li>
</ul>
<p>Let's now learn how we can use this API to implement an in-place editable data table.</p>
<h1 id="creating-an-in-place-editable-table-using-formarray">Creating an in-place editable table using FormArray</h1>
<p>Let's first define a reactive form model, using the <code>FormBuilder</code> API:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=02.ts"></script>
<p>As we can see, we did not add any other controls to our form, except for the editable data table itself.</p>
<p>This is just to keep the example simple, but nothing would prevent us from adding any other form properties if we needed to.</p>
<p>In our case, all the controls inside the editable table are going to be inside the <code>FormArray</code> instance, built using the <code>fb.array()</code> API.</p>
<p>Initially, the <code>FormArray</code> instance is empty and contains no form controls, meaning that the editable table is initially empty.</p>
<p>We have added to the component a getter for the <code>lessons</code> property, in order to make it simple to access the <code>FormArray</code> instance in a simple and type-safe way.</p>
<p>Also, notice in the editable table screenshot shown earlier, that each row in the table contains two controls: a lesson title field and a lesson level (or difficulty) field.</p>
<p>We would like these fields to be part of the parent form of this component, and affect its validity state. If an error occurs in the title of one of the lessons, then the whole form should be considered invalid.</p>
<p>For this, we are going to create one <code>FormGroup</code> for each table row, and we are going to add to it two form fields, with their own form control validators.</p>
<h3 id="dynamically-adding-controls-to-a-formarray">Dynamically adding controls to a FormArray</h3>
<p>In order to add new rows to the table, we are going to need an Add Lesson button in our component template:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=03.html"></script>
<p>When this button gets clicked, we are going to trigger the following code:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=04.ts"></script>
<p>As we can see, in order to add a row to the table, we are first creating the form model of a simple form with only the two fields of each row: the lesson title and difficulty.</p>
<p>We then take this lesson row <code>FormGroup</code>, which is itself also a form control and we add it to the last position of the <code>FormArray</code> by using the <code>push</code> API.</p>
<p>Remember, we can add <em>any</em> form control to the <code>FormArray</code>, and this includes also form groups, which are also controls themselves.</p>
<h3 id="dynamically-removing-controls-from-a-formarray">Dynamically removing controls from a FormArray</h3>
<p>If you notice in the editable table screenshot shown earlier, every lesson row has a delete icon associated with it, that the user can use to delete the whole lesson row.</p>
<p>Here is what the click handler looks like for this button:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=05.ts"></script>
<p>In order to delete a lesson row, all we have to do is to use the <code>removeAt</code> API to remove the corresponding <code>FormGroup</code> from the <code>FormArray</code>, at a given row index.</p>
<p>Notice that in both the add lesson and remove lesson buttons, all we have to do to add or remove a row is to add or remove controls from the form model.</p>
<p>And this is because our UI model is built by looping through the <code>FormArray</code> elements, and by adding form controls accordingly.</p>
<h1 id="the-formarrayname-directive">The formArrayName directive</h1>
<p>To conclude our exercise, we will now show the full code of the editable table component, and review the template. Let's start with the component code:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=07.ts"></script>
<p>And here is what the editable table component template looks like:</p>
<script src="https://gist.github.com/jhades/a8a16ac802db0bdf0e38953fbbaa05dc.js?file=06.html"></script>
<p>Let's now break down what is going on here:</p>
<ul>
<li>This editable table is implemented using commonly used Angular Material components</li>
<li>We are applying the <code>formGroup</code> directive to a form container, and linking it to the parent form of the component</li>
<li>This means that the parent form will contain all the child controls of the form, including every control of every row created by the user</li>
<li>Inside the parent form, we apply the <code>formArrayName</code> directive, which links a container element to the <code>lessons</code> property of the form</li>
<li>This directive is what allows for the <code>FormArray</code> instance to track the values and validity state of its child components</li>
<li>We are then using <code>ngFor</code> to loop through the form controls of the lessons <code>FormArray</code></li>
<li>every control of the <code>FormArray</code> is a form group itself, containing two row controls (title and level)</li>
<li>We then use the <code>formGroup</code> directive to define a nested form for every table row, containing two lesson row controls</li>
<li>We then use the <code>formControlName</code> directive to bind the lesson fields to the template, like we usually do in any reactive form</li>
</ul>
<p>As we can see, our editable table form is simply a form with a list of nested child forms, one form per table row. And each table row form contains two controls inside it.</p>
<p>And with this, our in-place editable table is fully implemented! The user can freely add and remove lesson rows to the form.</p>
<p>The parent form will <em>only</em> be considered valid once every row added by the user is filled in with valid values.</p>
<h2 id="summary">Summary</h2>
<p>Let's quickly summarize everything that we have learned about <code>FormArray</code>, and do one final comparison to <code>FormGroup</code>.</p>
<p>As we can see, the <code>FormArray</code> construct is very powerful and comes in especially handy in situations where we want to build our form model in a more dynamic way.</p>
<h3 id="when-to-use-an-angular-formarray-vs-a-formgroup">When to use an Angular FormArray vs a FormGroup?</h3>
<p>When building the model of an Angular form, most of the time we want to use a <code>FormGroup</code> and not a <code>FormArray</code>, so that should be the default choice.</p>
<p>As we can see, the <code>FormArray</code> container is ideal for those rarer situations when we don't know the number of form controls upfront or their names.</p>
<p>The <code>FormArray</code> container is ideal for more dynamic situations where the content of the form is in general being defined at runtime, depending on user interaction or even backend data.</p>
<p>In our example, we have used <code>FormArray</code> to implement an in-place editable table, because we believe that is its most common use case.</p>
<p>In the table example, the controls in the <code>FormArray</code> were <code>FormGroup</code> instances, containing form controls themselves, but notice that this is not mandatory.</p>
<p>A <code>FormArray</code> can contain any type of controls inside it, and this includes plain form controls, <code>FormGroup</code> instances and even other <code>FormArray</code> instances.</p>
<p>With <code>FormArray</code>, you can implement in Angular all sorts of advanced dynamic form scenarios, but keep in mind that unless you really need the power of<br>
<code>FormArray</code>, <code>FormGroup</code> will be the correct choice for most cases.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular Forms, we recommend checking the <a href="https://angular-university.io/course/angular-forms-course" target="_blank" rel="noopener">Angular Forms In Depth</a> course, where all sorts of advanced forms topics (including <code>FormArray</code>) are covered in much more detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular File Upload: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-file-upload/</link>
      <guid isPermaLink="false">600a95862bf7e500399b3574</guid>
      <pubDate>Thu, 28 Jan 2021 15:07:29 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Core</category>
      <description>Everything that you need to know to build a fully functional custom file upload component in Angular.</description>
      <content:encoded><![CDATA[<p>This post will cover everything that you need to know in practice in order to handle all sorts of file upload scenarios in an Angular application.</p>
<p>We are going to learn how to build a fully functional Angular file upload component, that requires a file of a given extension to be uploaded and sends the file to a backend via an HTTP POST call.</p>
<p>This custom component is going to have an upload loading indicator, and it's going to support upload cancelation as well. We are going to give also an example (in Node) of how to handle the file in the backend.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>How to upload files in a browser</li>
<li>Building the user interface of a file upload component</li>
<li>Selecting a file from the file system using a file upload dialog</li>
<li>Uploading a file to the backend using the Angular HTTP Client</li>
<li>How to display a file upload progress indicator</li>
<li>How to cancel an ongoing file upload</li>
<li>Handling the uploaded file on a Node backend</li>
<li>How to upload multiple files</li>
<li>Summary</li>
</ul>
<p>So without further ado, let's get started learning how to build an Angular file upload component!</p>
<h2 id="how-to-upload-files-in-a-browser">How to Upload Files in a Browser</h2>
<p>In order to build an Angular file upload component, we need to first understand how to upload files in plain HTML and Javascript <em>only</em>, and take it from there.</p>
<p>The key ingredient for uploading files in a browser is a plain HTML input of type file:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=01.html"></script>
<p>This input will allow the user to open a browser file selection dialog and select one or more files (by default, only one file). Here is what this input looks like:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/angular-file-upload/file-upload-input.png" alt="A plain HTML file upload input" loading="lazy" decoding="async"></p>
<p>With this file input box, you can select a file from your file system, and then with a bit of Javascript, you can already send it to a backend.</p>
<h4 id="why-don-t-we-see-file-inputs-very-often">Why don't we see file inputs very often?</h4>
<p>The problem with this plain file input is that by default it's very hard to style. Some styles applied to it can't be changed, and we can't even change the text on the button!</p>
<p>This is default browser behavior that can't be changed, and that is why we usually don't see this plain file input on all the interfaces that we use daily, like Gmail, etc.</p>
<p>Because this file input is impossible to style properly, the most common option is to actually <em>never show it</em> to the end-user, as we will see.</p>
<h4 id="how-does-the-input-of-type-file-work">How does the input of type file work?</h4>
<p>When the user chooses a file using the file upload dialog, an event of type<br>
<code>change</code> will be emitted. This event will then contain the list of files that the user selected on the <code>target.files</code> property.</p>
<p>Here is the output that we see on the console after the user selects a file:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=02.ts"></script>
<p>When the <code>change</code> event gets triggered, the file is <strong>not</strong> automatically uploaded to the backend by the browser. Instead, we will need to trigger an HTTP request ourselves, in response to the <code>change</code> event.</p>
<p>Now that we know how all the standard file upload browser functionality works, let's see how can we build a nice Angular component to encapsulate it.</p>
<h2 id="building-the-user-interface-of-a-file-upload-component">Building the User Interface of a File Upload Component</h2>
<p>Because a plain input of type file is impossible to style properly, what we end up doing is hiding it from the user, and then building an alternative file upload UI that uses the file input behind the scenes.</p>
<p>Here is what the template of an initial file upload component could look like:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=03.html"></script>
<p>This user interface is split up into two separate parts. On top, we have a plain file input, that is used to open the file upload dialog and handle the <code>change</code> event.</p>
<p>This plain input text is hidden from the user, as we can see in the component CSS:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=04.css"></script>
<p>Below the hidden file input, we have the <code>file-upload</code> container div, which contains the actual UI that the user will see on the screen.</p>
<p>As an example, we have built this UI with Angular Material components, but of course, the alternative file upload UI could take any form that you like.</p>
<p>This UI could be a dialog, a drag and drop zone, or like in the case of our component, just a styled button:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/angular-file-upload/angular-file-upload-component.png" alt="Example of an Angular Material file upload component" loading="lazy" decoding="async"></p>
<p>Notice in the component template how the upload blue button and the invisible file input are linked. When the user clicks on the blue button, a click handler triggers the file input via <code>fileUpload.click()</code>.</p>
<p>The user will then choose a file from the file upload dialog, and the <code>change</code> event will be triggered and handled by <code>onFileSelected()</code>.</p>
<h2 id="uploading-a-file-to-the-backend-using-the-angular-http-client">Uploading a file to the backend using the Angular HTTP Client</h2>
<p>Let's now have a look at our component class and the implementation of<br>
<code>onFileSelected()</code>:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=05.ts"></script>
<p>Here is what is going in this component:</p>
<ul>
<li>we are getting a reference to the files that the user selected by accessing the <code>event.target.files</code> property.</li>
<li>we then build a form payload by using the <code>FormData</code> API. This is a standard browser API, it's not Angular-specific.</li>
<li>we then use the Angular HTTP client to create an HTTP request and send the file to the backend</li>
</ul>
<p>At this point, we would already have a working file upload component. But we want to take this component one step further. We want to be able to display a progress indicator to the user, and also support upload cancelation.</p>
<h2 id="how-to-display-a-file-upload-progress-indicator">How to Display a File Upload Progress Indicator</h2>
<p>We are going to add a few more elements to the UI of our file upload component. Here is the final version of the file upload component template:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=06.html"></script>
<p>The two main elements that we have added to the UI are:</p>
<ul>
<li>An Angular Material progress bar, which is visible only while the file upload is still in progress.</li>
<li>A cancel upload button, also only visible when an upload is still ongoing</li>
</ul>
<h4 id="how-to-know-how-much-of-the-file-has-been-uploaded">How to know how much of the file has been uploaded?</h4>
<p>The way that we implement the progress indicator, is by using the <code>reportProgress</code> feature of the Angular HTTP client.</p>
<p>With this feature, we can get notified of the progress of a file upload via multiple events emitted by the HTTP Observable.</p>
<p>To see it in action, let's have a look at the final version of the file upload component class, with all its features implemented:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=07.ts"></script>
<p>As we can see, we have set the <code>reportProgress</code> property to true in our HTTP call, and we have also set the <code>observe</code> property to the value <code>events</code>.</p>
<p>This means that, as the POST call continues, we are going to receive event objects reporting the progress of the HTTP request.</p>
<p>These events will be emitted as values of the <code>http$</code> Observable, and come in different types:</p>
<ul>
<li>events of type <code>UploadProgress</code> report the percentage of the file that has already been uploaded</li>
<li>events of types <code>Response</code> report that the upload has been completed</li>
</ul>
<p>Using the events of type <code>UploadProgress</code>, we are saving the ongoing upload percentage in a member variable <code>uploadProgress</code>, which we then use to update the value of the progress indicator bar.</p>
<p>When the upload either completes or fails, we need to hide the progress bar from the user.</p>
<p>We can make sure that we do so by using the RxJs <code>finalize</code> operator, which is going to call the <code>reset()</code> method in both cases: upload success or failure.</p>
<h2 id="how-to-cancel-an-ongoing-file-upload">How to Cancel an Ongoing File Upload</h2>
<p>In order to support file upload cancellation, all we have to is keep a reference to the RxJs Subscription object that we get when the <code>http$</code> Observable gets subscribed to.</p>
<p>In our component, we store this subscription object in the <code>uploadSub</code> member variable.</p>
<p>While the upload is still in progress, the user might decide to cancel it by clicking on the cancel button. Then the <code>cancelUpload()</code> upload method is going to get triggered and the HTTP request can be canceled by unsubscribing from the <code>uploadSub</code> subscription.</p>
<p>This unsubscription will trigger the immediate cancelation of the ongoing file upload.</p>
<h2 id="how-to-accept-only-files-of-a-certain-type">How to accept only files of a certain type</h2>
<p>In the final version of our file upload component, we can require the user to upload a file of a certain type, by using the <code>requiredFileType</code> property:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=9.html"></script>
<p>This property is then passed directly to the <code>accept</code> property of the file input in the file upload template, forcing the user to select a png file from the file upload dialog.</p>
<h2 id="how-to-upload-multiple-files">How to Upload Multiple Files</h2>
<p>By default, the browser file selection dialog will allow the user to select only one file for upload.</p>
<p>But using the <code>multiple</code> property, we can allow the user to select multiple files instead:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=8.html"></script>
<p>Notice that this would need a completely different UI than the one that we have built. A styled upload button with a progress indicator only works well for the upload of a single file.</p>
<p>For a multi-file upload scenario, there are a variety of UIs that could be built: a floating dialog with the upload progress of all files, etc.</p>
<h2 id="handling-the-uploaded-file-on-a-node-backend">Handling the uploaded file on a Node backend</h2>
<p>The way that you handle the uploaded file in your backend depends on the technology that you use, but let's give a quick example of how to do it if using Node and the Express framework.</p>
<p>We need to first install the <code>express-fileupload</code> package. We can then add this package as a middleware in our Express application:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=10.ts"></script>
<p>From here, all we have to do is define an Express route to handle the file upload requests:</p>
<script src="https://gist.github.com/jhades/e6efe40ab1584451dd26cca76e48b800.js?file=11.ts"></script>
<h2 id="summary">Summary</h2>
<p>The best way to handle file upload in Angular is to build one or more custom components, depending on the supported upload scenarios.</p>
<p>A file upload component needs to contain internally an HTML input of type file, that allows the user to select one or more files from the file system.</p>
<p>This file input should be hidden from the user as it's not styleable and replaced by a more user-friendly UI.</p>
<p>Using the file input in the background, we can get a reference to the file via the <code>change</code> event, which we can then use to build an HTTP request and send the file to the backend.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular, we recommend checking the <a href="https://angular-university.io/course/angular-course" target="_blank" rel="noopener">Angular Core Deep Dive</a> course, where we will cover all of the advanced Angular features in detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Custom Form Controls: Complete Guide</title>
      <link>https://blog.angular-university.io/angular-custom-form-controls/</link>
      <guid isPermaLink="false">60004e7a4c7d6a0039195238</guid>
      <pubDate>Thu, 21 Jan 2021 15:02:46 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Forms</category>
      <description>Build a fully functional custom form control, compatible with template-driven and reactive forms, as well as with all built-in and custom form validators.</description>
      <content:encoded><![CDATA[<p>The Angular Forms and ReactiveForms modules come with a series of built-in directives that make it very simple to bind standard HTML elements like inputs, checkboxes, text areas, etc. to a form group.</p>
<p>Besides these standard HTML elements, we might also want to use custom form controls, like dropdowns, selection boxes, toggle buttons, sliders, or many other types of commonly used custom form components.</p>
<p>For these custom controls, we would like to have the ability to configure them as form fields using the <em>exact same directives</em> (<code>ngModel</code>, <code>formControl</code>,<br>
<code>formControlName</code>) as we use for standard input boxes.</p>
<p>In this guide, we are going to learn exactly how to take an existing custom form control component and make it <strong>fully compatible with the Angular Forms API</strong>, so that the component can participate in the parent form validation and value tracking mechanisms.</p>
<p>This means that:</p>
<ul>
<li>if we are using template driven forms, we will be able to plug the custom component to the form simply by using <code>ngModel</code></li>
<li>and in the case of reactive forms, we will be able to add the custom component to the form using <code>formControlName</code> (or <code>formControl</code>)</li>
</ul>
<p>We will be building in this guide a simple quantity selector component, that can be used to increment or decrement a value. The component will be part of a form and will be marked as in error in case that the counter does not match a valid range.</p>
<p>The new custom form control will be fully compatible with the built-in Angular Forms Validators <code>required</code>, <code>max</code> as well as any other built-in or custom validators.</p>
<p>We will also learn in this guide how to create <strong>reusable nested forms</strong>, which are form sections that be reused in many different forms.</p>
<p>The typical example of such type of nested forms is an address sub-form, and we are going to build one in this post.</p>
<h2 id="table-of-contents">Table Of Contents</h2>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>How do standard form controls work?</li>
<li>What are form control value accessors?</li>
<li>Introduction to the <code>ControlValueAccessor</code> interface</li>
<li>Implementing the <code>ControlValueAccessor</code> interface step-by-step</li>
<li>Implementing the <code>Validator</code> interface</li>
<li>Demo of a fully functional custom form control</li>
<li>How to implement nested form groups (an address nested form)</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Forms, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-forms/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know for creating our own custom form controls and nested forms!</p>
<h2 id="how-do-standard-form-controls-work">How do standard form controls work?</h2>
<p>In order to know how to build a custom form control, we need to first understand how the built-in form controls work.</p>
<p>The built-in form controls target native HTML elements such as inputs, text areas, checkboxes, etc.</p>
<p>Here is an example of a simple form with a couple of plain HTML form fields:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=01.html"></script>
<p>As we can see, we have here a couple of standard form controls, with the<br>
<code>formControlName</code> property applied to it. And this is how the HTML element gets binded to the form.</p>
<p>Whenever the user interacts with the form inputs, the form value and validity state will be automatically re-calculated.</p>
<p>So how does this all work under the hood then?</p>
<h2 id="what-are-control-value-accessors">What are control value accessors?</h2>
<p>What happens is that, under the hood, the Angular forms module is applying to each native HTML element a built-in Angular directive, which will be responsible for tracking the value of the field, and communicate it back to the parent form.</p>
<p>This type of special directive is known as a control value accessor directive.</p>
<p>Take for example the checkbox field of the form above. There is a built-in directive which is part of the reactive forms module that is designed to specifically track the value of a checkbox, and nothing more.</p>
<p>Here is the simplified declaration of this directive:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=02.ts"></script>
<p>As we can see by the selector, this value tracking directive specifically targets HTML inputs of type checkbox only, but only if the <code>ngModel</code>, <code>formControl</code> or<br>
<code>formControlName</code> properties are applied to it.</p>
<p>If this directive only targets checkboxes, then what about all the other types of form controls, like text inputs or text areas?</p>
<p>Well, each of those control types has their own value accessor directive, which is different than <code>CheckboxControlValueAccessor</code>.</p>
<p>All of those directives are built-in into the Angular Forms module and cover only the standard HTML form controls.</p>
<p>This means that if we want to implement our own custom form control, we are going to have to implement a custom value accessor for it as well.</p>
<h2 id="the-custom-form-control-that-we-will-build">The custom form control that we will build</h2>
<p>Let's say that we want to build a custom form control that represents a numeric counter with increase and decrease buttons, for selecting an order quantity for example.</p>
<p>Each time that the buttons are pressed, the counter should be incremented or decremented by a configurable amount.</p>
<p>We can configure this control to specify a maximum value allowed for the form field, and mark it as invalid if the range is not met.</p>
<p>Here is what the numeric form control will look like:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/custom-form-controls/angular-custom-form-control.png" alt="Angular Custom Form Control" loading="lazy" decoding="async"></p>
<p>And here is the implementation code for this simple component, without any form functionality added yet:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=03.ts"></script>
<p>In its current form, this component is not compatible with either template-driven or reactive forms.</p>
<p>We would like to be able to add this component to a form in a very similar way to how we add a standard HTML input to a form, by either adding the<br>
<code>formControlName</code> or <code>ngModel</code> directives to it:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=04.html"></script>
<p>We would also like for this component to be compatible with the built-in validators, and use them to make the field mandatory and set a maximum value:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=05.ts"></script>
<p>But in the case of the current version of our control, if we would try to do so we would get an error:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">ERROR Error: Must supply a value for form control with name: &#39;totalQuantity&#39;.
at forms.js:2692
at forms.js:2639
at Array.forEach (&lt;anonymous&gt;)
at FormGroup._forEachChild (forms.js:2639)
at FormGroup._checkAllValuesPresent (forms.js:2690)
at FormGroup.setValue (forms.js:2490)
at CreateCourseStep1Component.ngOnInit (create-course-step-1.component.ts:51)
at callHook (core.js:3405)
at callHooks (core.js:3375)
at executeInitAndCheckHooks (core.js:3327)
</code></pre></div>
<p>In order to fix this error, and make the <code>choose-quantity</code> component compatible with Angular Forms, we need to give this form control a value accessor, just like the case of native HTML elements like text inputs, checkboxes, etc.</p>
<p>In order to do that, we are going to make the component implement the<br>
<code>ControlValueAccessor</code> interface.</p>
<h2 id="understanding-the-controlvalueaccessor-interface">Understanding the ControlValueAccessor interface</h2>
<p>Let's go over the methods of the ControlValueAccessor interface. Remember, they are not meant to be called directly by our code as these are framework callbacks.</p>
<p>All of these methods are meant to be called only by the Forms module at runtime, and they are meant to facilitate communication between our form control and the parent form.</p>
<p>Here are the methods of this interface, and how they work:</p>
<ul>
<li><strong>writeValue</strong>: this method is called by the Forms module to write a value into a form control</li>
<li><strong>registerOnChange</strong>: When a form value changes due to user input, we need to report the value back to the parent form. This is done by calling a callback, that was initially registered with the control using the registerOnChange method</li>
<li><strong>registerOnTouched</strong>: When the user first interacts with the form control, the control is considered to have the status touched, which is useful for styling. In order to report to the parent form that the control was touched, we need to use a callback registered using the registerOnToched method</li>
<li><strong>setDisabledState</strong>: form controls can be enabled and disabled using the Forms API. This state can be transmitted to the form control via the setDisabledState method</li>
</ul>
<p>And here is the component, with the <code>ControlValueAccessor</code> interface already implemented:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=06.ts"></script>
<p>Let's now go through each of the methods one by one, and explain how they were implemented.</p>
<h2 id="implementing-writevalue">Implementing writeValue</h2>
<p>The <code>writeValue</code> method is called by the Angular forms module whenever the parent form wants to set a value in the child control.</p>
<p>In the case of our component, we will take the value and assign it directly to the internal <code>quantity</code> property:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=07.ts"></script>
<h2 id="implementing-registeronchange">Implementing registerOnChange</h2>
<p>The parent form can set a value in the child control using <code>writeValue</code>, but what about the other way around?</p>
<p>If the user interacts with the form control and increments or decrements the counter value, then the new value needs to be communicated back to the parent form.</p>
<p>The child control can notify the parent form that a new value is available via the use of a <em>callback</em> function.</p>
<p>The first step for this to work, is for the parent form to register the callback function with the child control, bt using the <code>registerOnChange</code> method:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=08.ts"></script>
<p>As we can see, when this method is called, we are going to receive our callback function, which we then save for later in a member variable.</p>
<p>The <code>onChange</code> member variable is declared as a function, and initialized with an empty function, meaning a function with an empty body.</p>
<p>This way, if our program by some reason calls the function before the<br>
<code>registerOnChange</code> call was made, we won't run into any errors.</p>
<p>When the value of the counter is changed by either clicking on the increment or decrement buttons, then we need to notify the parent form that a new value is available.</p>
<p>We are going to do so by calling the callback function and reporting the new value:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=09.ts"></script>
<h2 id="implementing-registerontouched">Implementing registerOnTouched</h2>
<p>Besides reporting new values back to the parent form, we also need to inform the parent form when the child control has been considered to be touched by the user.</p>
<p>When the form is initialized, every form control (and the form group as well) is considered to be in status untouched, and the <code>ng-untouched</code> CSS class is applied to the form group and also to each of its individual child controls.</p>
<p>But when a child control gets touched by the user, meaning the user has tried to interact with it at least once, then the whole form is considered touched as well, meaning that the <code>ng-touched</code> CSS class gets applied to the form.</p>
<p>These touched/untouched CSS classes are important for styling error messages in a form, so our custom form control needs to support this as well.</p>
<p>Like before, we need to have a callback registered, so that the child control can report its touched status back to the parent form:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=10.ts"></script>
<p>We now need to call this callback when the control is considered touched, and this will happen whenever the user clicks any of the increment or decrement buttons at least once:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=11.ts"></script>
<p>As we can see, when one of the two buttons gets clicked for the first time, we are going to call the <code>onTouched</code> callback once, and the form control will now be considered as touched by the parent form.</p>
<p>The custom form control will have the <code>ng-touched</code> CSS class applied to it as expected:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/custom-form-controls/angular-custom-form-control-touched-state.png" alt="Angular Custom Form Control in status touched" loading="lazy" decoding="async"></p>
<h2 id="implementing-setdisabledstate">Implementing setDisabledState</h2>
<p>Its also possible for the parent form to enable or disable any of its child controls, by calling the <code>setDisabledState</code> method. We can keep the disabled status in the member variable <code>disabled</code>, and use it in order to turn on and off the increment/decrement functionality:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=12.ts"></script>
<h3 id="dependency-injection-configuration-for-controlvalueaccessor">Dependency injection configuration for ControlValueAccessor</h3>
<p>Finally, the last piece of the puzzle to implement the <code>ControlValueAccessor</code> interface correctly, is to register the custom form control as a known value accessor in the dependency injection system:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=14.ts"></script>
<p>Without this configuration in place, our custom form control will <em>not</em> work correctly.</p>
<p>So what does this configuration do? We are adding the component to the list of known value accessors, that are all registered with the <code>NG_VALUE_ACCESSOR</code> unique dependency injection key (also known as an injection token).</p>
<p>Notice the <code>multi</code> flag set to true, this means that this dependency provides a list of values, and not only one value. This is normal because there are many value accessors registered with Angular Forms besides our own.</p>
<p>For example, all the built-in value accessors for standard text inputs, checkboxes, etc. are also registered under <code>NG_VALUE_ACCESSOR</code>.</p>
<p>This way, whenever the Angular forms module needs the full list of all the value accessors available, all it has to do is to inject <code>NG_VALUE_ACCESSOR</code>.</p>
<p>With this, our component is now capable of setting the value of a property in a form.</p>
<p>More than that, the component is now capable of participating in the form validation process and is already fully compatible with for example the built-in <code>required</code> and <code>max</code> validators.</p>
<p>But what if the component needs to have its own built-in validation rules, that are <em>always active</em> for every instance of the component, independently of the form configuration?</p>
<h2 id="introduction-to-the-validator-interface">Introduction to the Validator interface</h2>
<p>In the case of our custom form control, we would like for it to ensure that the quantity is positive. If it's not, then the form field should be marked as in error, and this should be true for all instances of the component, always.</p>
<p>In order to implement this logic, we are going to have our component implement the <code>Validator</code> interface. This interface contains only two methods:</p>
<ul>
<li><strong>validate</strong>: This method is used to validate the current value of the form control. This method will be called whenever a new value is reported to the parent form. The method needs to return null if no errors are found, or an error object containing all the details needed to correctly display a meaningful error message to the user.</li>
<li><strong>registerOnValidatorChange</strong>: This will register a callback that will allow us to trigger the validation of the custom control on demand. We don't need to do this when new values are emitted, as validation is already triggered in that case. We only need to call this method if some other input that also affects the behavior of <code>validate</code> has changed</li>
</ul>
<p>Let's now see how to implement this interface, and do a final demo of the working component.</p>
<h2 id="implementing-the-validator-interface">Implementing the Validator interface</h2>
<p>The only method of <code>Validator</code> that we really have to implement is the <code>validate</code> method:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=15.ts"></script>
<p>In this implementation, we return <code>null</code> if the value is valid, and an error object containing all the details about the error.</p>
<p>In the case of our component, we didn't need to implement<br>
<code>registerOnValidatorChange</code>, as implementing this method is optional.</p>
<p>We only need this method if for example, our component had configurable validation rules, that depended on some of the component inputs. If that would be the case, we could trigger a new validation on demand in case one of the validation inputs changes.</p>
<p>In our case, the <code>validate</code> implementation only depends on the current value of the control, so we didn't need to implement <code>registerOnValidatorChange</code> and grab that callback for further use.</p>
<p>In order for the Validator interface to work properly, we also need to register our custom component with the <code>NG_VALIDATORS</code> injection token:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=16.ts"></script>
<p>Notice that without registering this class properly in <code>NG_VALIDATORS</code>,<br>
the <code>validate</code> method will never get called.</p>
<h2 id="demo-of-a-fully-functional-custom-form-control">Demo of a fully functional custom form control</h2>
<p>And with the two interfaces <code>ControlValueAccessor</code> and <code>Validator</code>, we now have a fully functional custom form control, compatible with both reactive and template-driven forms, and capable of both setting the value of a form property and participating in the form validation process.</p>
<p>Here is the final code:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=17.ts"></script>
<p>Let's now test this component at runtime, by adding it to a form with a couple of standard validators:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=05.ts"></script>
<p>As we can see, we are making the field mandatory, and setting a maximum value of 100. The initial value of the control is 60, which is a valid value.</p>
<p>But what happens if we set the value to for example 110? The form will then become invalid, and the <code>totalQuantity</code> control will have an error associated with it.</p>
<p>We can see the error by checking the value of the <code>errors</code> property of<br>
<code>form.controls['totalQuantity']</code>:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=18.json"></script>
<p>As we can see, the <code>Validators.max(100)</code> built-in validator kicked in and marked our custom form control in error as expected.</p>
<p>But what if instead, we set the quantity value to for example a negative -10 value? Here is what the <code>errors</code> property of our control will now look like:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=19.json"></script>
<p>As we can see, now the <code>validate</code> method created a <code>ValidationErrors</code> object, which was then set as part of the errors of the form control.</p>
<p>We now have a fully functional custom form control, compatible with template-driven forms, reactive forms, and all built-in validators.</p>
<h2 id="how-to-implement-nested-form-groups-an-address-nested-form">How to implement nested form groups (an address nested form)</h2>
<p>A very common forms use case that can be implemented with what we have learned so far are nested form groups, that can be reused across multiple forms.</p>
<p>A good example of this is an address form, with all the usual address fields:</p>
<p><img src="https://angular-university.s3-us-west-1.amazonaws.com/blog-images/custom-form-controls/nested-form-example.png" alt="Angular Nested Form Example - an Address form" loading="lazy" decoding="async"></p>
<p>Now imagine that your application has many different forms where an address is required. We wouldn't want to repeat all the code needed for displaying and validating those fields across every form.</p>
<p>Instead, what we would like to do is to create a reusable form section under the form of an Angular component, that we could then plug into multiple forms, sort of a nested reusable sub-form.</p>
<p>Here is how we would like to use such an address form component:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=20.html"></script>
<p>As we can see, we would like to make our address form component fully compatible with Angular forms, meaning that it should support the <code>ngModel</code>,<br>
<code>formControl</code> and <code>formControlName</code> directives, and be able to participate in the validation of the parent form.</p>
<p>Sounds familiar?</p>
<p>Indeed, all we have to do for that is to implement just like we did before the<br>
<code>ControlValueAcessor</code> and <code>Validator</code> interfaces. So how will this work?</p>
<p>First, we need to define the view of our nested address form component:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=21.html"></script>
<p>As we can see, our nested address form is also a from group itself, and it also uses Angular forms internally to collect the values of every address field and validate their values.</p>
<p>The <code>form</code> object already contains all the information about the values and validity state of this subform. We can now use this information to quickly implement both the <code>ControlValueAccessor</code> and <code>Validator</code> interfaces:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=22.ts"></script>
<p>Here are some important notes about this implementation:</p>
<ul>
<li>the form address component uses itself a form internally for doing all the form validation using a series of built-in validators</li>
<li>we are using the principle of delegation as much as possible here. For example, we are getting all the information that we need from the <code>form</code> object</li>
<li>As an example of the delegation principle, we are implementing <code>writeValue</code> using <code>form.setValue</code>, and we are implementing <code>setDisabledState</code> by using <code>form.enable()</code> and <code>form.disable()</code></li>
<li>We are using the <code>valueChanges</code> Observable to know when a new value is emitted by the the address form, and calling the <code>onChange</code> callback to notify the parent form.</li>
<li>As we are manually subscribing to the <code>valueChanges</code> Observable, we are also unsubscribing from it using <code>OnDestroy</code>, to avoid any memory leaks</li>
<li>we are implementing the <code>validate</code> method by checking if the embedded form controls have any errors and passing them to the <code>ValidationErrors</code> object</li>
</ul>
<h3 id="demo-of-the-nested-address-form">Demo of the nested address form</h3>
<p>If we try to fill in the values of the address form, we are going to see that they are reported back to the parent form, and show up under the <code>address</code> property.</p>
<p>This is <code>value</code> property of the parent form containing <code>address-form</code>, after typing in an address:</p>
<script src="https://gist.github.com/jhades/9f1b0a12436085f852ea337ecea90e73.js?file=23.ts"></script>
<h2 id="summary">Summary</h2>
<p>Every form control has linked to it a control value accessor, which is responsible for the interaction between the form control and the parent form.</p>
<p>And this includes all the standard HTML form controls like text inputs, checkboxes, etc., for which the forms module provides built-in control value accessors.</p>
<p>For a custom form control, we will have to build our own control value accessor by implementing the <code>ControlValueAccessor</code> interface, and if we want the control to do custom value validation then we need to implement the <code>Validator</code> interface.</p>
<p>We can also use the same technique to implement nested form groups (like an address sub-form), that can be reused across multiple forms.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular Forms, we recommend checking the <a href="https://angular-university.io/course/angular-forms-course" target="_blank" rel="noopener">Angular Forms In Depth</a> course, where validators, custom form controls, and many other advanced form topics are covered in detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Angular Custom Form Validators:  Complete Guide</title>
      <link>https://blog.angular-university.io/angular-custom-validators/</link>
      <guid isPermaLink="false">5ffc6bd74c7d6a0039194d46</guid>
      <pubDate>Wed, 13 Jan 2021 08:53:50 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>
      <category>Angular Forms</category>
      <description>All about custom form validators, including synchronous and asynchronous, field-level, form-level, for both template-driven and reactive forms.</description>
      <content:encoded><![CDATA[<p>When building large scale forms with the Angular Forms module, the available built-in validators (such as making a field required, etc.) usually won't be sufficient, and so you will have to develop your own <strong>custom form validation rules</strong>.</p>
<p>In this post, you will learn everything that you need to know in order to implement your own custom form validators, including both synchronous and asynchronous, field-level, form-level, and both for template-driven and reactive forms.</p>
<h2 id="table-of-contents">Table of Contents</h2>
<p>This post will cover the following topics:</p>
<ul>
<li>What is a form field validator?</li>
<li>Custom Validators for reactive forms</li>
<li>Displaying error messages for custom validators</li>
<li>Custom Validators for template-driven forms</li>
<li>Comparing validation in template-driven vs reactive forms</li>
<li>Form-level (multi-field) Validators</li>
<li>Asynchronous Validators</li>
<li>How to use the updateOn field property</li>
<li>Summary</li>
</ul>
<p>This post is part of our ongoing series on Angular Forms, you can find all the articles available <a href="https://blog.angular-university.io/tag/angular-forms/">here</a>.</p>
<p>So without further ado, let's get started learning everything that we need to know to write our own custom form validators!</p>
<h2 id="what-is-a-form-field-validator">What is a form field Validator?</h2>
<p>If you have used either the Angular Forms or ReactiveForms modules, you will have noticed that every form has a couple of important properties:</p>
<ul>
<li>the form value, consisting of the values of all the individual form fields</li>
<li>a form validity state, which is true if all the form fields are valid, and false if at least one of the forms fields is invalid</li>
</ul>
<p>Each form field has its own set of business validation rules: the fields can be mandatory, have a minimum length of 10 characters, etc.</p>
<p>Here is an example of a simple reactive form, with a couple of standard validators:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=01.html"></script>
<p>As we can see, this is a simple login form with an email and password fields. We don't see any business validation rules because this is a reactive form, so all validation rules are defined on the component, and not on the template.</p>
<p>Here is the corresponding component class:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=02.ts"></script>
<p>There are a lot of validation rules being used here. Let's go through them one at a time, starting with the simpler ones.</p>
<p>In this particular reactive form, we are using the <code>FormBuilder</code> API in order to define our form fields and validation rules in a concise way.</p>
<p>For example, the email field is marked as mandatory via the <code>Validators.required</code> validator, and it also needs to follow the format of a valid email, due to the use of the <code>Validators.email</code> validator.</p>
<p>These are two examples of the several built-in validators that we have available to use, right out of the box.</p>
<h4 id="so-how-do-these-validators-work-what-is-a-validator">So how do these validators work, what is a validator?</h4>
<p>A form field validator is <em>a function</em> that the form can call in order to decide if a given form field is valid or not.</p>
<p>A validator function returns true if the form field is valid according to the validator rules, or false otherwise.</p>
<p>A validator can be plugged in directly into a reactive form simply by adding it to the validators list. Each form field has its own list of separate validators.</p>
<h4 id="two-alternative-syntaxes-for-configuring-validators">Two alternative syntaxes for configuring validators</h4>
<p>If you noticed, the validation rules for the email and the password fields were configured in a slightly different way.</p>
<p>The password field was configured in the way that you are probably the most used to, by using the <code>FormBuilder</code> API simplified array syntax:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=03.ts"></script>
<p>With this syntax, each form field has an array containing both the initial value of the form field and its list of synchronous validators.</p>
<p>Although this syntax is compact, it might become a bit difficult to read for fields with a larger number of validators.</p>
<p>An alternative syntax is the one used by the email field:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=04.ts"></script>
<p>In this alternative and more powerful syntax, but also slightly more verbose, the second value of the configuration array (after the initial form field value) is a configuration object containing 3 properties that we can optionally use:</p>
<ul>
<li><strong>validators</strong>: contains the list of synchronous validators for the form field</li>
<li><strong>asyncValidators</strong>: contains the list asynchronous validators for the form field (not used in this example)</li>
<li><strong>updateOn</strong>: specifies the moment when the form should be updated with the new form field value and recalculate the field validity (more on this later).</li>
</ul>
<p>Our advice is to switch to the more powerful syntax with the configuration object as soon as you need to, either to set the <code>updateOn</code> property or to make the form field definition more readable.</p>
<p>Notice also, in the login reactive form, that next to the standard built-in <code>required</code> and <code>minLength</code> validators of the password field, we have a non-standard validator <code>createPasswordStrengthValidator()</code>.</p>
<p>This is a custom validator, that we have written ourselves.</p>
<h2 id="custom-validators-for-reactive-forms">Custom Validators for Reactive Forms</h2>
<p>The password strength validator ensures that the password has enough strength besides a minimum length. The password strength might be used to require the password to contain not only lowercase characters but also upper case and numeric characters, for example.</p>
<p>With reactive forms, writing a custom validator is as easy as writting a new function:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=05.ts"></script>
<p>Let's break down what is going on here. As we can see, the<br>
<code>createPasswordStrengthValidator()</code> function is <em>not</em> the validator function itself.</p>
<p>This is actually a <em>validator creation function</em>, that returns as its output the validator. So it's a function that returns a function, as we can see this by its return type <code>ValidatorFn</code>.</p>
<p>The validator creation function can have any arguments needed to set up the validator (in this case no arguments were needed), and returns as the output the validator function itself.</p>
<p>The validator function is then going to be called by the form in order to determine if the form field value is valid or not.</p>
<p>And as we can see, the validator function needs to follow certain conventions.</p>
<h3 id="how-to-write-a-validator-function">How to write a Validator function</h3>
<p>The form field validator function, returned by the validator creation function, needs to follow these rules:</p>
<ul>
<li>only one input argument is expected, which is of type <code>AbstractControl</code>. The validator function can obtain the value to be validated via the <code>control.value</code> property</li>
<li>The validator function needs to return null if no errors were found in the field value, meaning that the value is valid</li>
<li>If any validation errors are found, the function needs to return an object of type <code>ValidationErrors</code></li>
<li>The <code>ValidationErrors</code> object can have as properties the multiple errors found (usually just one), and as values the details about each error.</li>
<li>The value of the <code>ValidationErrors</code> object can be an object with any properties that we want, allowing us to provide a lot of useful information about the error if needed</li>
<li>If we just want to indicate that an error occurred, without providing further details, we can simply return <code>true</code> as the value of an error property in the <code>ValidationErrors</code> object</li>
</ul>
<p>In the particular case of our password strength validator function, we are checking for the presence of all required characters, and in the end, we are either:</p>
<ul>
<li>returning <code>null</code> if the password is valid and no errors were found</li>
<li>returning <code>{passwordStrength:true}</code> as an output error object, in case that the password is not strong enough</li>
</ul>
<p>As we can see, we are only returning a boolean flag in the error object indicating that an error was found, without more details. But we could instead also return an error object similar to this one:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=06.ts"></script>
<p>This <code>ValidationErrors</code> object can have any form that we need. We can return nested objects if we need to, in order to convey all the necessary information about what caused the error.</p>
<p>Once we have a new custom validator function written, all we have to do is plug it in our reactive form:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=07.ts"></script>
<p>Let's remember, the <code>createPasswordStrengthValidator()</code> function did not need input arguments, but we could have defined any arguments that we needed in order to perform the validation, and pass them in this function call.</p>
<h2 id="displaying-error-messages-for-custom-validators">Displaying error messages for custom Validators</h2>
<p>In order to inform the user that there is a problem with the password strength, we can add the following message to the template:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=10.ts"></script>
<p>As we can see, the <code>ValidationErrors</code> object that we returned as the output of our custom validator was added to the pasword field errors object.</p>
<p>If the password is not strong enough, the <code>ngIf</code> condition will turn to true and the error message will then be shown to the user.</p>
<h2 id="custom-validators-for-template-driven-forms">Custom Validators for Template-Driven Forms</h2>
<p>For template-driven forms, it takes a bit more work to define a custom form field validator.</p>
<p>With template driven forms, all the business validation rules are defined at the level of the template using directives, and not at the level of the component class.</p>
<p>For example, here is what the same login form would look like in its template-driven version:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=08.html"></script>
<p>As we can see, in the case of template-driven forms, there is a lot more going on in the template.</p>
<p>For example, we can see the standard <code>required</code>, <code>minlength</code>, <code>maxlength</code> and <code>email</code> directives applied to the email and password fields.</p>
<p>The way that these directives work, is that they use internally the corresponding validator functions <code>Validators.required</code>, <code>Validators.minlength</code>, and<br>
<code>Validators.maxLength</code>.</p>
<p>Notice also the non-standard <code>passwordStrength</code> directive, applied to the password field. This one we will have to build ourselves!</p>
<p>So in the case of template-driven forms, besides the validator function, we also need to create a custom directive to go along with it.</p>
<p>Otherwise, we won't be able to use our custom validators in our template-driven forms.</p>
<h3 id="how-to-write-a-custom-validator-directive">How to write a custom Validator directive</h3>
<p>Let's have a look at what the custom form field <code>passwordStrength</code> directive looks like:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=09.ts"></script>
<p>Let's break this down step by step, starting with the implementation of the validation functionality itself:</p>
<ul>
<li>in order to implement a custom validation directive, we need to implement the <code>Validator</code> interface, which only has the <code>validate</code> method</li>
<li>the <code>validate</code> method is going to call the validation creation function, and pass the control reference (the password control in this case) to the validator</li>
<li>the validator is going to return <code>null</code> if the password valid is false, on a <code>ValidationErrors</code> error object otherwise</li>
</ul>
<p>But implementing the <code>Validator</code> interface is not enough to make this a valid custom validation directive. We also have to configure it properly in the Angular dependency injection system.</p>
<h4 id="understanding-the-di-configuration-of-a-custom-validator-directive">Understanding the DI configuration of a custom validator directive</h4>
<p>The Angular Forms module needs to know what are the multiple custom validation directives available. It does so by asking the dependency injection system for the <code>NG_VALIDATORS</code> injection token (a sort of unique dependency injection key, that uniquely identifies a dependency).</p>
<p>This dependency in of type <code>multi:true</code> meaning that it includes multiple values, and not just one value. This is to be expected, as there are many custom validator directives, and not just one.</p>
<p>We can see in our directive declaration that we are creating a new provider, meaning that we are setting up a new value in the DI system and we are making the <code>PasswordStrengthDirective</code> available to be instantiated by the DI system if needed.</p>
<p>Because the <code>NG_VALIDATORS</code> provider is of type <code>multi:true</code>, we are adding the<br>
<code>PasswordStrengthDirective</code> to the list of existing custom validation directives, instead of replacing the new list with a single value.</p>
<p>Notice that adding the proper DI configuration to your custom validation directive is essential for it to work. Without this, the <code>validate()</code> method simply won't get triggered.</p>
<h2 id="comparing-custom-validation-in-template-driven-vs-reactive-forms">Comparing custom Validation in template-driven vs reactive forms</h2>
<p>As we can see, it takes a bit more work and also more general Angular knowledge to implement custom validation in template-driven forms.</p>
<p>With reactive forms, all we have to do is to write a function. But in template-driven forms, besides implementing a Validator function, we also have to know how to write our own custom directive and know how to configure the dependency injection system.</p>
<p>But even though things are a bit harder in template-driven forms, it's still quite doable.</p>
<p>If you want to learn more about the <a href="https://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/">differences between template-driven and reactive forms</a>, you can check out our previous article.</p>
<h2 id="form-level-multi-field-validators">Form-level (multi-field) Validators</h2>
<p>Besides being able to define custom validators at the level of each field, we can also define custom validators at the level of the form.</p>
<p>This is very useful in order to do for example multi-field validation, when a validation rule can be true or false depending on the values of multiple different form fields, as opposed to just one field.</p>
<p>Here is an example, imagine a reactive form that takes in two separate input dates, a start date and an end date:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=11.ts"></script>
<p>In order for the form to be considered valid, it's not enough to make the two dates mandatory. We also need to put in place a validation rule that says that the start date should be before the end date.</p>
<p>And this can't be done with a custom validator at the level of the form field. Instead, we need to define a validator <em>at the level of the form</em>.</p>
<p>And we can do so also by defining a custom validator function, in a similar way to field-level validators.</p>
<p>Here is an example of a form-level validator for checking if the start date is before the end date:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=12.ts"></script>
<p>As we can see, defining a form-level validator is almost the same as a field-level validator! The only difference is that the input of the function is a<br>
<code>FormGroup</code> object instead of a form control.</p>
<p>Using the <code>FormGroup</code>, we can easily access any value of the form and compare multiple values together, like for example the start date and end date fields.</p>
<p>Once the form-level validator function is written, all we have to do it is to apply it in the configuration of the form:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=14.ts"></script>
<p>As we can see, this type of validator needs to be configured at the level of the form group as a separate configuration object, and not at the level of any of the form fields.</p>
<p>This form-level configuration object can also take the <code>asyncValidators</code> and<br>
<code>updateOn</code> property, which we will cover in a moment.</p>
<h2 id="asynchronous-form-field-validators">Asynchronous form field Validators</h2>
<p>All of the custom validators that we have been showing so far are <em>synchronous</em>, meaning that the new validity state is immediately calculated by the validator as soon as the validator function is called.</p>
<p>For the case of simple validators like mandatory, minimum length, password strength etc. this makes sense, but there are situations where we would like for this new validity state to be calculated in an <em>asynchronous</em> way.</p>
<p>Imagine that in order to determine the new validity state, we would need to perform some sort of asynchronous operation, such as for example calling a backend or using any sort of promise-based library.</p>
<p>In that case, synchronous validators would simply not work. One such example would be the case of the email field. In the case of a user creation form, we want the form button to be enabled only if the user email is not yet used on the backend.</p>
<p>In order to check if the user already exists, we need to call the backend and query the database, which requires an asynchronous operation, and that's where asynchronous validators come in.</p>
<p>Here is what our user creation form would look like:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=15.html"></script>
<p>As we can see, an error message will be shown to the user informing that an user with that email already exists, if the property <code>userExists</code> is present at the level of the field errors object.</p>
<p>Let's now see what the component class looks like, focusing on the email field only:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=16.ts"></script>
<p>Synchronous and asynchronous validators cannot be mixed, so that is why we have used the more powerful configuration object syntax to<br>
bind an asynchronous validator to the email field.</p>
<p>We are passing to the validator creation function <code>userExistsValidator</code> an input argument of type <code>UserService</code>. This is the service that we are going to be using to call the backend and check if a user with the same email already exists.</p>
<h3 id="how-to-write-an-asynchronous-validator">How to write an Asynchronous Validator</h3>
<p>And here is what our <code>userExistsValidator</code> asynchronous validator looks like:</p>
<script src="https://gist.github.com/jhades/b179cbd8b6e28fa227b6e4e4231538df.js?file=17.ts"></script>
<p>As we can see, this is very similar to a normal validator like we have implemented before. The main difference is that the type returned by the validator creation function <code>userExistsValidator()</code> is of type <code>AsyncValidatorFn</code>.</p>
<p>This means that the validation function itself needs to return either a promise or an Observable that emits a value of type <code>ValidationErrors</code>.</p>
<p>In the case of our implementation, we have used Observables, by calling the HTTP based UserService that called our backend and checked if the user exists on the database.</p>
<p>The last piece of the puzzle for fully understanding custom validators, is that<br>
<code>updateOn</code> property that we have used on the email field.</p>
<h2 id="how-to-use-the-updateon-field-property">How to use the updateOn field property</h2>
<p>The <code>updateOn</code> property can be used both at the level of the form control, like the email field, or at the level of the whole form, like in the case of the start date / end date example.</p>
<p>The <code>updateOn</code> property is useful to define <em>when</em> the form value should be updated with the latest form field value.</p>
<p>When we link a form control such as a text input box to a form model, either by using <code>ngModel</code>, <code>formControl</code>, or <code>formControlName</code>, what happens is that the value of the form control will start to be tracked by the parent form.</p>
<p>When the user starts typing new values or changing the value of the form field, that new value will then be communicated back to the parent form.</p>
<p>The parent form will then need to update its global <code>form.value</code> property, but it will also need to determine if the new value is valid or not.</p>
<p>And for that, it needs to call the validators of the form field and calculate a new field validity state, which will then be used to calculate the new form validity state.</p>
<p>The question is, <em>when</em> will the new value of the form field be communicated back to the parent form?</p>
<p>This is important because by default the value is communicated as quickly as possible. For example, in the case of an input text field, this will by default be communicated with each key pressed by the user, which might be too fast for certain scenarios.</p>
<p>For example, in the case of our <code>userExistsValidator</code>, this would be too much because a new HTTP request to the backend would be triggered with each key pressed.</p>
<p>Instead, we would like the request to be done to the backend only when the user finishes typing the email, so that is why we have set the <code>updateOn</code> property to <code>blur</code>.</p>
<p>This way, only when the user finishes interacting with the email field and moves to another field (either by tabbing away or clicking elsewhere), will then a single HTTP request be triggered to validate the email.</p>
<p>Note that while the asynchronous validation is in progress, the <code>ng-pending</code> css state class will be applied to the email field.</p>
<p>This can be used for styling the email field and informing the user that the validation is in progress if needed.</p>
<h4 id="when-to-set-updateon-to-blur">When to set <code>updateOn</code> to <code>blur</code>?</h4>
<p>Besides asynchronous validators, we might also want to set <code>updateOn</code> to <code>blur</code> due to the behavior of certain plain synchronous validators as well.</p>
<p>For example, something as simple as the <code>email</code> validator might not work well if it gets triggered with every key pressed.</p>
<p>When the user starts typing an email, the email will not immediately be valid, which might cause an error message like &quot;The email is invalid&quot; to be shown to the user while he is still typing and then disappear as the email is fully typed, which might be a bit awkward for the user.</p>
<h4 id="what-are-the-different-values-that-updateon-can-take">What are the different values that <code>updateOn</code> can take?</h4>
<p>There are three values that we can set for the <code>updateOn</code> property:</p>
<ul>
<li><code>change</code>: this is the default value. It means that the form will be updated with every new field value (causing all field validators to be triggered). For a select box or checkbox this will happen when the user chooses a new value, but for a text box this will happen with every key pressed</li>
<li><code>blur</code>: this means that the form will be updated with the new field value only when the field is blurred, meaning that the user either tabbed away or clicked elsewhere on the page</li>
<li><code>submit</code>: this is rarely used, but its available if needed. This means that the form will only be updated with the new value immediately after the form gets submitted.</li>
</ul>
<p>The <code>updateOn</code> property can be defined both at the level of the form field and also at level of the overall form itself.</p>
<h2 id="summary">Summary</h2>
<p>Let's now quickly summarize everything that we have learned about custom form validators:</p>
<ul>
<li>a custom validator is a function that validates the value of a form field according to a business rule, such as form example the field is mandatory or the password needs to have a certain strength</li>
<li>With reactive forms, it's much easier to define custom validators. All we have to do is to define a function, and plug it into the form configuration.</li>
<li>with template-driven forms, it's also possible to do custom form validation but it's a bit trickier. We will have to define besides the validator function a custom directive and plug it into the dependency injection system</li>
<li>Validators can also be defined at the form level, and this is especially useful for writing validators that depend on the values of multiple fields, such as for example to ensure that the password and confirm password fields in a user creation form are identical</li>
<li>certain validators can need to perform an asynchronous operation, like calling a backend or a promise-based library. This can be implemented by having the validator return either a promise or an observable</li>
<li>For validation to work properly, it's usually necessary to fine-tune exactly when the validators of a field are triggered. This can be done using the <code>updateOn</code> property</li>
</ul>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about Angular Forms, we recommend checking the <a href="https://angular-university.io/course/angular-forms-course" target="_blank" rel="noopener">Angular Forms In Depth</a> course, where validators, custom form controls, and many other advanced form topics are covered in detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on Angular, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>And if you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
    <item>
      <title>RxJs Error Handling: Complete Practical Guide</title>
      <link>https://blog.angular-university.io/rxjs-error-handling/</link>
      <guid isPermaLink="false">5fdb35f02a541e003930cad0</guid>
      <pubDate>Mon, 16 Jul 2018 22:00:00 GMT</pubDate>
      <dc:creator>Angular University</dc:creator>

      <description>Error handling is an essential part of RxJs, as we will need it in just about any reactive program that we write.</description>
      <content:encoded><![CDATA[<p>Error handling is an essential part of RxJs, as we will need it in just about any reactive program that we write.</p>
<p>Error handling in RxJS is likely not as well understood as other parts of the library, but it's actually quite simple to understand if we <em>focus on understanding first</em> the Observable contract in general.</p>
<p>In this post, we are going to provide a complete guide containing the <strong>most common error handling strategies</strong> that you will need in order to cover most practical scenarios, starting with the basics (the Observable contract).</p>
<h3 id="table-of-contents">Table Of Contents</h3>
<p>In this post, we will cover the following topics:</p>
<ul>
<li>The Observable contract and Error Handling</li>
<li>RxJs subscribe and error callbacks</li>
<li>The catchError Operator</li>
<li>The Catch and Replace Strategy</li>
<li>throwError and the Catch and Rethrow Strategy</li>
<li>Using catchError multiple times in an Observable chain</li>
<li>The finalize Operator</li>
<li>The Retry Strategy</li>
<li>Then retryWhen Operator</li>
<li>Creating a Notification Observable</li>
<li>Immediate Retry Strategy</li>
<li>Delayed Retry Strategy</li>
<li>The delayWhen Operator</li>
<li>The timer Observable creation function</li>
<li>Running Github repository (with code samples)</li>
<li>Conclusions</li>
</ul>
<p>So without further ado, let's get started with our RxJs Error Handling deep dive!</p>
<h3 id="the-observable-contract-and-error-handling">The Observable Contract and Error Handling</h3>
<p>In order to understand error handling in RxJs, we need to first understand that any given stream <em>can only error out once</em>. This is defined by the Observable contract, which says that a stream can emit zero or more values.</p>
<p>The contract works that way because that is just how all the streams that we observe in our runtime work in practice. Network requests can fail, for example.</p>
<p>A stream can also complete, which means that:</p>
<ul>
<li>the stream has ended its lifecycle without any error</li>
<li>after completion, the stream will not emit any further values</li>
</ul>
<p>As an alternative to completion, a stream can also error out, which means that:</p>
<ul>
<li>the stream has ended its lifecycle with an error</li>
<li>after the error is thrown, the stream will not emit any other values</li>
</ul>
<p>Notice that completion or error are mutually exclusive:</p>
<ul>
<li>if the stream completes, it cannot error out afterwards</li>
<li>if the streams errors out, it cannot complete afterwards</li>
</ul>
<p>Notice also that there is no obligation for the stream to complete <em>or</em> error out, those two possibilities are optional. But only one of those two <em>can</em> occur, not both.</p>
<p>This means that when one particular stream errors out, we cannot use it anymore, according to the Observable contract. You must be thinking at this point, how can we recover from an error then?</p>
<h3 id="rxjs-subscribe-and-error-callbacks">RxJs subscribe and error callbacks</h3>
<p>To see the RxJs error handling behavior in action, let's create a stream and subscribe to it. Let's remember that the subscribe call takes three optional arguments:</p>
<ul>
<li>a success handler function, which is called each time that the stream emits a value</li>
<li>an error handler function, that gets called only if an error occurs. This handler receives the error itself</li>
<li>a completion handler function, that gets called only if the stream completes</li>
</ul>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=01.ts"></script>
<h4 id="completion-behavior-example">Completion Behavior Example</h4>
<p>If the stream does <em>not</em> error out, then this is what we would see in the console:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">HTTP response {payload: Array(9)}
HTTP request completed.
</code></pre></div>
<p>As we can see, this HTTP stream emits only one value, and then it completes, which means that no errors occurred.</p>
<p>But what happens if the stream throws an error instead? In that case, we will see the following in the console instead:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-1.png" alt="RxJs Error Handling console output" loading="lazy" decoding="async"></p>
<p>As we can see, the stream emitted no value and it immediately errored out. After the error, no completion occurred.</p>
<h4 id="limitations-of-the-subscribe-error-handler">Limitations of the subscribe error handler</h4>
<p>Handling errors using the subscribe call is sometimes all that we need, but this error handling approach is limited. Using this approach, we cannot, for example, recover from the error or emit an alternative fallback value that replaces the value that we were expecting from the backend.</p>
<p>Let's then learn a few operators that will allow us to implement some more advanced error handling strategies.</p>
<h3 id="the-catcherror-operator">The catchError Operator</h3>
<p>In synchronous programming, we have the option to wrap a block of code in a try clause, catch any error that it might throw with a catch block and then handle the error.</p>
<p>Here is what the synchronous catch syntax looks like:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=02.ts"></script>
<p>This mechanism is very powerful because we can handle in one place <em>any</em> error that happens inside the try/catch block.</p>
<p>The problem is, in Javascript many operations are asynchronous, and an HTTP call is one such example where things happen asynchronously.</p>
<p>RxJs provides us with something close to this functionality, via the RxJs catchError Operator.</p>
<h4 id="how-does-catcherror-work">How does catchError work?</h4>
<p>As usual and like with any RxJs Operator, catchError is simply a function that takes in an input Observable, and outputs an Output Observable.</p>
<p>With each call to catchError, we need to pass it a function which we will call the error handling function.</p>
<p>The catchError operator takes as input an Observable that <em>might</em> error out, and starts emitting the values of the input Observable in its output Observable.</p>
<p>If no error occurs, the output Observable produced by catchError works exactly the same way as the input Observable.</p>
<h4 id="what-happens-when-an-error-is-thrown">What happens when an error is thrown?</h4>
<p>However, if an error occurs, then the catchError logic is going to kick in. The catchError operator is going to take the error and pass it to the error handling function.</p>
<p>That function is expected to return an Observable which is going to be a <em>replacement Observable</em> for the stream that just errored out.</p>
<p>Let's remember that the input stream of catchError has errored out, so according to the Observable contract we cannot use it anymore.</p>
<p>This replacement Observable is then going to be subscribed to and its values are going to be used <em>in place</em> of the errored out input Observable.</p>
<h3 id="the-catch-and-replace-strategy">The Catch and Replace Strategy</h3>
<p>Let's give an example of how catchError can be used to provide a replacement Observable that emits fallback values:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=03.ts"></script>
<p>Let's break down the implementation of the catch and replace strategy:</p>
<ul>
<li>we are passing to the catchError operator a function, which is the error handling function</li>
<li>the error handling function is not called immediately, and in general, it's usually <em>not</em> called</li>
<li><em>only</em> when an error occurs in the input Observable of catchError, will the error handling function be called</li>
<li>if an error happens in the input stream, this function is then returning an Observable built using the <code>of([])</code> function</li>
<li>the <code>of()</code> function builds an Observable that emits only one value (<code>[]</code>) and then it completes</li>
<li>the error handling function returns the recovery Observable (<code>of([])</code>), that gets subscribed to by the catchError operator</li>
<li>the values of the recovery Observable are then emitted as replacement values in the output Observable returned by catchError</li>
</ul>
<p>As the end result, the <code>http$</code> Observable <strong>will not error out</strong> anymore! Here is the result that we get in the console:</p>
<div class="code-block"><button type="button" class="code-copy" aria-label="Copy code">Copy</button><pre class="language-none"><code class="language-none">HTTP response []
HTTP request completed.
</code></pre></div>
<p>As we can see, the error handling callback in <code>subscribe()</code> is not invoked anymore. Instead, here is what happens:</p>
<ul>
<li>the empty array value <code>[]</code> is emitted</li>
<li>the <code>http$</code> Observable is then completed</li>
</ul>
<p>As we can see, the replacement Observable was used to provide a default fallback value (<code>[]</code>) to the subscribers of <code>http$</code>, despite the fact that the original Observable <em>did</em> error out.</p>
<p>Notice that we could have also added some local error handling, before returning the replacement Observable!</p>
<p>And this covers the Catch and Replace Strategy, now let's see how we can also use catchError to <em>rethrow</em> the error, instead of providing fallback values.</p>
<h3 id="the-catch-and-rethrow-strategy">The Catch and Rethrow Strategy</h3>
<p>Let's start by noticing that the replacement Observable provided via catchError can itself also error out, just like any other Observable.</p>
<p>And if that happens, the error will be propagated to the subscribers of the output Observable of catchError.</p>
<p>This error propagation behavior gives us a mechanism to rethrow the error caught by catchError, after handling the error locally. We can do so in the following way:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=04.ts"></script>
<h4 id="catch-and-rethrow-breakdown">Catch and Rethrow breakdown</h4>
<p>Let's break down step-by-step the implementation of the Catch and Rethrow Strategy:</p>
<ul>
<li>just like before, we are catching the error, and returning a replacement Observable</li>
<li>but this time around, instead of providing a replacement output value like <code>[]</code>, we are now handling the error locally in the catchError function</li>
<li>in this case, we are simply logging the error to the console, but we could instead add any local error handling logic that we want, such as for example showing an error message to the user</li>
<li>We are then returning a replacement Observable that this time was created using throwError</li>
<li>throwError creates an Observable that never emits any value. Instead, it errors out immediately using the same error caught by catchError</li>
<li>this means that the output Observable of catchError will also error out with the exact same error thrown by the input of catchError</li>
<li>this means that we have managed to successfully <em>rethrow</em> the error initially thrown by the input Observable of catchError to its output Observable</li>
<li>the error can now be further handled by the rest of the Observable chain, if needed</li>
</ul>
<p>If we now run the code above, here is the result that we get in the console:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-2.png" alt="RxJs Error Handling console output" loading="lazy" decoding="async"></p>
<p>As we can see, the same error was logged both in the catchError block and in the subscription error handler function, as expected.</p>
<h3 id="using-catcherror-multiple-times-in-an-observable-chain">Using catchError multiple times in an Observable chain</h3>
<p>Notice that we can use catchError multiple times at different points in the Observable chain if needed, and adopt different error strategies at each point in the chain.</p>
<p>We can, for example, catch an error up in the Observable chain, handle it locally and rethrow it, and then further down in the Observable chain we can catch the same error again and this time provide a fallback value (instead of rethrowing):</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=05.ts"></script>
<p>If we run the code above, this is the output that we get in the console:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-3.png" alt="RxJs Map Operator marble diagram" loading="lazy" decoding="async"></p>
<p>As we can see, the error was indeed rethrown initially, but it never reached the subscribe error handler function. Instead, the fallback <code>[]</code> value was emitted, as expected.</p>
<h3 id="the-finalize-operator">The Finalize Operator</h3>
<p>Besides a catch block for handling errors, the synchronous Javascript syntax also provides a finally block that can be used to run code that we <em>always</em> want executed.</p>
<p>The finally block is typically used for releasing expensive resources, such as for example closing down network connections or releasing memory.</p>
<p>Unlike the code in the catch block, the code in the finally block will get executed independently if an error is thrown or not:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=06.ts"></script>
<p>RxJs provides us with an operator that has a similar behavior to the finally functionality, called the finalize Operator.</p>
<blockquote>
<p>Note: we cannot call it the finally operator instead, as finally is a reserved keyword in Javascript</p>
</blockquote>
<h4 id="finalize-operator-example">Finalize Operator Example</h4>
<p>Just like the catchError operator, we can add multiple finalize calls at different places in the Observable chain if needed, in order to make sure that the multiple resources are correctly released:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=07.ts"></script>
<p>Let's now run this code, and see how the multiple finalize blocks are being executed:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-4.png" alt="RxJs Error Handling console output" loading="lazy" decoding="async"></p>
<p>Notice that the last finalize block is executed <em>after</em> the subscribe value handler and completion handler functions.</p>
<h3 id="the-retry-strategy">The Retry Strategy</h3>
<p>As an alternative to rethrowing the error or providing fallback values, we can also simply <em>retry</em> to subscribe to the errored out Observable.</p>
<p>Let's remember, once the stream errors out we cannot recover it, but nothing prevents us from subscribing <em>again</em> to the Observable from which the stream was derived from, and create another stream.</p>
<p>Here is how this works:</p>
<ul>
<li>we are going to take the input Observable, and subscribe to it, which creates a new stream</li>
<li>if that stream does <em>not</em> error out, we are going to let its values show up in the output</li>
<li>but if the stream does error out, we are then going to subscribe <em>again</em> to the input Observable, and create a brand new stream</li>
</ul>
<h4 id="when-to-retry">When to retry?</h4>
<p>The big question here is, <em>when</em> are we going to subscribe again to the input Observable, and retry to execute the input stream?</p>
<ul>
<li>are we going to retry that immediately?</li>
<li>are we going to wait for a small delay, hoping that the problem is solved and then try again?</li>
<li>are we going to retry only a limited amount of times, and then error out the output stream?</li>
</ul>
<p>In order to answer these questions, we are going to need a second auxiliary Observable, which we are going to call the Notifier Observable. It's the Notifier<br>
Observable that is going to determine <em>when</em> the retry attempt occurs.</p>
<p>The Notifier Observable is going to be used by the retryWhen Operator, which is the heart of the Retry Strategy.</p>
<h3 id="rxjs-retrywhen-operator-marble-diagram">RxJs retryWhen Operator Marble Diagram</h3>
<p>To understand how the retryWhen Observable works, let's have a look at its marble diagram:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-5.png" alt="RxJs retryWhen Operator" loading="lazy" decoding="async"></p>
<p>Notice that the Observable that is being re-tried is the 1-2 Observable in the second line from the top, and <em>not</em> the Observable in the first line.</p>
<p>The Observable on the first line with values r-r is the Notification Observable, that is going to determine <em>when</em> a retry attempt should occur.</p>
<h4 id="breaking-down-how-retrywhen-works">Breaking down how retryWhen works</h4>
<p>Let's break down what is going in this diagram:</p>
<ul>
<li>The Observable 1-2 gets subscribed to, and its values are reflected immediately in the output Observable returned by retryWhen</li>
<li>even after the Observable 1-2 is completed, it can still be re-tried</li>
<li>the notification Observable then emits a value <code>r</code>, way after the Observable 1-2 has completed</li>
<li>The value emitted by the notification Observable (in this case <code>r</code>) could be <em>anything</em></li>
<li>what matters is the moment when the value <code>r</code> got emitted, because that is what is going to trigger the 1-2 Observable to be retried</li>
<li>the Observable 1-2 gets subscribed to again by retryWhen, and its values are again reflected in the output Observable of retryWhen</li>
<li>The notification Observable is then going to emit again another <code>r</code> value, and the same thing occurs: the values of a newly subscribed 1-2 stream are going to start to get reflected in the output of retryWhen</li>
<li>but then, the notification Observable eventually completes</li>
<li>at that moment, the ongoing retry attempt of the 1-2 Observable is completed early as well, meaning that only the value 1 got emitted, but not 2</li>
</ul>
<p>As we can see, retryWhen simply retries the input Observable each time that the Notification Observable emits a value!</p>
<p>Now that we understand how retryWhen works, let's see how we can create a Notification Observable.</p>
<h3 id="creating-a-notification-observable">Creating a Notification Observable</h3>
<p>We need to create the Notification Observable directly in the function passed to the retryWhen operator. This function takes as input argument an Errors Observable, that emits as values the errors of the input Observable.</p>
<p>So by subscribing to this Errors Observable, we know exactly <em>when</em> an error occurs. Let's now see how we could implement an immediate retry strategy using the Errors Observable.</p>
<h3 id="immediate-retry-strategy">Immediate Retry Strategy</h3>
<p>In order to retry the failed observable immediately after the error occurs, all we have to do is return the Errors Observable without any further changes.</p>
<p>In this case, we are just piping the tap operator for logging purposes, so the Errors Observable remains unchanged:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=08.ts"></script>
<p>Let's remember, the Observable that we are returning from the retryWhen function call <em>is</em> the Notification Observable!</p>
<p>The value that it emits is not important, it's only important <em>when</em> the value gets emitted because that is what is going to trigger a retry attempt.</p>
<h4 id="immediate-retry-console-output">Immediate Retry Console Output</h4>
<p>If we now execute this program, we are going to find the following output in the console:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-6.png" alt="retryWhen console output" loading="lazy" decoding="async"></p>
<p>As we can see, the HTTP request failed initially, but then a retry was attempted and the second time the request went through successfully.</p>
<p>Let's now have a look at the delay between the two attempts, by inspecting the network log:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-7.png" alt="RxJs retryWhen network log" loading="lazy" decoding="async"></p>
<p>As we can see, the second attempt was issued <em>immediately</em> after the error occurred, as expected.</p>
<h3 id="delayed-retry-strategy">Delayed Retry Strategy</h3>
<p>Let's now implement an alternative error recovery strategy, where we wait for example for 2 seconds after the error occurs, before retrying.</p>
<p>This strategy is useful for trying to recover from certain errors such as for example failed network requests caused by high server traffic.</p>
<p>In those cases where the error is intermittent, we can simply retry the same request after a short delay, and the request might go through the second time without any problem.</p>
<h3 id="the-timer-observable-creation-function">The timer Observable creation function</h3>
<p>To implement the Delayed Retry Strategy, we will need to create a Notification Observable whose values are emitted two seconds after each error occurrence.</p>
<p>Let's then try to create a Notification Observable by using the timer creation function. This timer function is going to take a couple of arguments:</p>
<ul>
<li>an initial delay, before which no values will be emitted</li>
<li>a periodic interval, in case we want to emit new values periodically</li>
</ul>
<p>Let's then have a look at the marble diagram for the timer function:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-8.png" alt="The timer Operator" loading="lazy" decoding="async"></p>
<p>As we can see, the first value 0 will be emitted only after 3 seconds, and then we have a new value each second.</p>
<p>Notice that the second argument is optional, meaning that if we leave it out our Observable is going to emit only one value (0) after 3 seconds and then complete.</p>
<p>This Observable looks like its a good start for being able to delay our retry attempts, so let's see how we can combine it with the retryWhen and delayWhen operators.</p>
<h3 id="the-delaywhen-operator">The delayWhen Operator</h3>
<p>One important thing to bear in mind about the retryWhen Operator, is that the function that defines the Notification Observable is only called <em>once</em>.</p>
<p>So we only get one chance to define our Notification Observable, that signals when the retry attempts should be done.</p>
<p>We are going to define the Notification Observable by taking the Errors Observable and applying it the delayWhen Operator.</p>
<p>Imagine that in this marble diagram, the source Observable a-b-c is the Errors Observable, that is emitting failed HTTP errors over time:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-9.png" alt="The timer Operator" loading="lazy" decoding="async"></p>
<h4 id="delaywhen-operator-breakdown">delayWhen Operator breakdown</h4>
<p>Let's follow the diagram, and learn how the delayWhen Operator works:</p>
<ul>
<li>each value in the input Errors Observable is going to be delayed before showing up in the output Observable</li>
<li>the delay <em>per each value</em> can be different, and is going to be created in a completely flexible way</li>
<li>in order to determine the delay, we are going to call the function passed to delayWhen (called the duration selector function) per each value of the input Errors Observable</li>
<li>that function is going to emit an Observable that is going to determine when the delay of each input value has elapsed</li>
<li>each of the values a-b-c has its own duration selector Observable, that will eventually emit one value (that could be anything) and then complete</li>
<li>when each of these duration selector Observables emits values, then the corresponding input value a-b-c is going to show up in the output of delayWhen</li>
<li>notice that the value <code>b</code> shows up in the output <em>after</em> the value <code>c</code>, this is normal</li>
<li>this is because the <code>b</code> duration selector Observable (the third horizontal line from the top) only emitted its value after the duration selector Observable of <code>c</code>, and that explains why <code>c</code> shows up in the output before <code>b</code></li>
</ul>
<h4 id="delayed-retry-strategy-implementation">Delayed Retry Strategy implementation</h4>
<p>Let's now put all this together and see how we can retry consecutively a failing HTTP request 2 seconds after each error occurs:</p>
<script src="https://gist.github.com/jhades/d699243fc450a85c2990d54b088c365a.js?file=09.ts"></script>
<p>Let's break down what is going on here:</p>
<ul>
<li>let's remember that the function passed to retryWhen is only going to be called once</li>
<li>we are returning in that function an Observable that will emit values whenever a retry is needed</li>
<li>each time that there is an error, the delayWhen operator is going to create a duration selector Observable, by calling the timer function</li>
<li>this duration selector Observable is going to emit the value 0 after 2 seconds, and then complete</li>
<li>once that happens, the delayWhen Observable knows that the delay of a given input error has elapsed</li>
<li>only once that delay elapses (2 seconds after the error occurred), the error shows up in the output of the notification Observable</li>
<li>once a value gets emitted in the notification Observable, the retryWhen operator will then and only then execute a retry attempt</li>
</ul>
<h4 id="retry-strategy-console-output">Retry Strategy Console Output</h4>
<p>Let's now see what this looks like in the console! Here is an example of an HTTP request that was retried 5 times, as the first 4 times were in error:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-10.png" alt="The timer Operator" loading="lazy" decoding="async"></p>
<p>And here is the network log for the same retry sequence:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-error-handling/rxjs-error-handling-11.png" alt="The timer Operator" loading="lazy" decoding="async"></p>
<p>As we can see, the retries only happened 2 seconds after the error occurred, as expected!</p>
<p>And with this, we have completed our guided tour of some of the most commonly used RxJs error handling strategies available, let's now wrap things up and provide some running sample code.</p>
<h3 id="running-github-repository-with-code-samples">Running Github repository (with code samples)</h3>
<p>In order to try these multiple error handling strategies, it's important to have a working playground where you can try handling failing HTTP requests.</p>
<p>This <a href="https://github.com/angular-university/rxjs-course/tree/1-operators-finished" target="_blank" rel="noopener">playground</a> contains a small running application with a backend that can be used to simulate HTTP errors either randomly or systematically. Here is what the application looks like:</p>
<p><img src="https://s3-us-west-1.amazonaws.com/angular-university/blog-images/rxjs-map-operators/09-demo-app.png" alt="RxJs sample application" loading="lazy" decoding="async"></p>
<h3 id="conclusions">Conclusions</h3>
<p>As we have seen, understanding RxJs error handling is all about understanding the fundamentals of the Observable contract first.</p>
<p>We need to keep in mind that any given stream can only error out <em>once</em>, and that is exclusive with stream completion; only one of the two things can happen.</p>
<p>In order to recover from an error, the only way is to somehow generate a replacement stream as an alternative to the errored out stream, like it happens in the case of the catchError or retryWhen Operators.</p>
<p>I hope that you have enjoyed this post, if you would like to learn a lot more about RxJs, we recommend checking the <a href="https://angular-university.io/course/rxjs-course" target="_blank" rel="noopener">RxJs In Practice Course</a> course, where lots of useful patterns and operators are covered in much more detail.</p>
<p>Also, if you have some questions or comments please let me know in the comments below and I will get back to you.</p>
<p>To get notified of upcoming posts on RxJs and other Angular topics, I invite you to subscribe to our newsletter:</p>
<script type="text/javascript" src="//static.mailerlite.com/data/webforms/432435/n5z2c6.js?v1"></script>
<p>If you are just getting started learning Angular, have a look at the <a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener">Angular for Beginners Course</a>:</p>
<p><a href="https://angular-university.io/course/getting-started-with-angular2" target="_blank" rel="noopener"><img src="https://angular-academy.s3.amazonaws.com/thumbnails/angular2-for-beginners-small-v2.png" alt="" loading="lazy" decoding="async"></a></p>
]]></content:encoded>
    </item>
  </channel>
</rss>
