<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Miloš Krstić on Medium]]></title>
        <description><![CDATA[Stories by Miloš Krstić on Medium]]></description>
        <link>https://medium.com/@mrkrsticmilos?source=rss-7aa9d7a6dbf1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1IQ-dRT37NTKXafupXnSkA.jpeg</url>
            <title>Stories by Miloš Krstić on Medium</title>
            <link>https://medium.com/@mrkrsticmilos?source=rss-7aa9d7a6dbf1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:34:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrkrsticmilos/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lazy load Material Dialogs]]></title>
            <link>https://blog.stackademic.com/lazy-load-material-dialogs-31284f61e984?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/31284f61e984</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[angular-material]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 06:52:46 GMT</pubDate>
            <atom:updated>2026-01-31T07:43:13.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBYM6rK5-TOqYsusjAsQow.png" /></figure><p>Once again I will explore the topic of <strong>Token Aliasing</strong> in Angular in practice.</p><p>Recently I needed to implement Confirmation Modals on different projects. On each project I had to implement it using the <em>Material Dialog</em>.</p><p>If my confirmation dialog looks something like this:</p><pre>import {<br>  MAT_DIALOG_DATA,<br>  MatDialogActions,<br>  MatDialogContent,<br>  MatDialogModule<br>} from &#39;@angular/material/dialog&#39;;<br>import { MatButtonModule } from &#39;@angular/material/button&#39;;<br>import { JsonPipe } from &#39;@angular/common&#39;;<br><br>export const MY_DIALOG_ID = &#39;MY_DIALOG_ID&#39;;<br><br>@Component({<br>  imports: [<br>    MatDialogModule,<br>    MatButtonModule,<br>    MatDialogContent,<br>    MatDialogActions,<br>    JsonPipe<br>  ],<br>  inlineTemplate: `<br>    &lt;mat-dialog-content&gt;<br>      &lt;p&gt;Are you sure you want to remove this data?&lt;/p&gt;<br>      &lt;pre&gt;{{ data | json }}&lt;/pre&gt;<br>    &lt;/mat-dialog-content&gt;<br>    &lt;mat-dialog-actions&gt;<br>      &lt;button mat-button mat-dialog-close&gt;Cancel&lt;/button&gt;<br>      &lt;button mat-button color=&quot;warn&quot; [mat-dialog-close]=&quot;true&quot;&gt;Remove&lt;/button&gt;<br>    &lt;/mat-dialog-actions&gt;<br>  `,<br>)<br>export class MyDialog {<br>  readonly data = inject(MAT_DIALOG_DATA);<br>}</pre><p>The most common approach I’ve seen is to use some <em>RxJS</em> magic to open the modal:</p><pre>@Component({<br>  //...<br>})<br>export class Dashboard {<br>  private readonly dialog = inject(MatDialog);<br>  private readonly destroyRef = inject(DestroyRef)<br><br>  openDialog(data: any): void {<br>    this.dialog.open(MyDialog, {<br>      data<br>    })<br>    .afterClosed()<br>    .pipe(<br>      first(),<br>      filter(Boolean),<br>      tap(() =&gt; { /* do something */ }<br>      takeUntilDestroyed(this.destroyRef)<br>    )<br>    .subscribe()<br>  }<br>//...<br>}</pre><p>Which is kind of okay if you are into <em>RxJS</em> like me.</p><p>Alternative is to use declarative way and define your modal in the template with input handling the shown state.</p><p>But in both cases we are importing unnecessary bundle which is something I don’t like doing. :)</p><p>Is there a different way?</p><p>Of course there is. Once again we are going to leverage the power of <strong>Dependency Injection mechanism</strong> in Angular.</p><h3>Lazy loading the Dialog component</h3><p>Inspiration could be found in the Angular itself. I am talking about lazy loading of the (<em>standalone</em>) components in routing configuration.</p><pre>export const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    loadComponent: () =&gt;<br>      import(&#39;./features/dashboard/dashboard.ts&#39;).then(<br>        m =&gt; m.Dashboard<br>      )<br>  },</pre><p>Routes are registered with provideRouter function in Application config:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter(routes)<br>  ]<br>}</pre><p>We are going to do something similar here. We are going to register our dialog components and tell the <em>Angular Dependency Injection</em> about them.</p><p>First step is to create a <strong>lightweight</strong> <em>Injection Token</em>:</p><pre>import { InjectionToken, Type } from &#39;@angular/core&#39;;<br><br>export interface DialogComponentToken {<br>  id: string;<br>  loadComponent: () =&gt; Promise&lt;Type&lt;unknown&gt;&gt;;<br>}<br><br>export const DIALOG_COMPONENT_TOKEN = new InjectionToken&lt;<br>  DialogComponentToken[]<br>&gt;(&#39;DialogComponentToken&#39;);</pre><p>Let’s break this piece of code down:</p><p>We need an <em>identifier</em> for our component which will be used to determine which modal should be opened.</p><p>Also, we need a <em>loader</em> function for the chosen component bundle.</p><p>Notice that the type of the <em>Injection Token</em> is actually an <strong>array</strong>.</p><h4>Provide the dialog components</h4><p>In the same file where we defined the <em>DIALOG_COMPONENT_TOKEN</em> we can define our function for providing the components:</p><pre>import { InjectionToken, makeEnvironmentProviders, Type } from &#39;@angular/core&#39;;<br>import { MY_DIALOG_ID } from &#39;../features/dashboard/my-dialog&#39;;<br><br>export interface DialogComponent {<br>  id: string;<br>  loadComponent: () =&gt; Promise&lt;Type&lt;unknown&gt;&gt;;<br>}<br><br>export const DIALOG_COMPONENT_TOKEN = new InjectionToken&lt;<br>  DialogComponent[]<br>&gt;(&#39;DIALOG_COMPONENT_TOKEN&#39;);<br><br>const dialogComponents: DialogComponent[] = [{<br>  id: MY_DIALOG_ID,<br>  loadComponent: () =&gt;<br>    import(<br>      &#39;../features/dashboard/my-dialog&#39;<br>    ).then(m =&gt; m.MyDialog)<br>}];<br><br>export function provideDialogComponents(<br>  components: DialogComponentToken[] = dialogComponents<br>) {<br>  return makeEnvironmentProviders(<br>    components.map(component =&gt; ({<br>      provide: DIALOG_COMPONENT_TOKEN,<br>      useValue: component,<br>      multi: true<br>    }))<br>  );<br>}</pre><p>Let’s go back to Application config file to register the provider for dialogs:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter(routes),<br>    provideDialogComponents()<br>  ]<br>}</pre><p><em>Great!</em> Next step is to open the modal based on an action in component.</p><p>We are going to refactor our <em>Dashboard</em> component a bit so we can load the bundle in <em>runtime</em>. First thing we are going to use is the <em>DI Injector</em>:</p><pre>@Component({<br>  //...<br>})<br>export class Dashboard {<br>  private readonly dialogRef = inject(MatDialog);<br>  private readonly injector = inject(Injector);<br><br>  async openDialog(data: any, dialogId = MY_DIALOG_ID): void {<br>    const dialogComponent = await this.injector.get(DIALOG_COMPONENT_TOKEN)<br>      .find((component) =&gt; component.id === dialogId)?.loadComponent();<br>    <br>    if (dialogComponent) {<br>      const result = await firstValueFrom(<br>        this.dialog.open(dialogComponent, {<br>          data<br>        }<br>      )<br>      .afterClosed());<br><br>      if (result) {<br>        /* Do something */<br>      }<br>    }<br>  }<br>//...<br>}</pre><p>Next step is to import the component lazily and pass the component to the Dialog service. Based on the <em>Dialog Identifier </em>we are determining which bundle should be loaded in runtime, not on page load.</p><p>Because the token is multi-provided at the environment level, resolving it at runtime does not eagerly load any dialog bundles — only the selected loader is executed.</p><p><em>This approach treats dialogs as </em><strong><em>intent-driven features</em></strong><em>, not static dependencies.</em></p><p><em>Angular’s DI system becomes a runtime registry instead of just a wiring mechanism.</em></p><p><em>The result is smaller initial bundles, clearer ownership of UI intent, and dialogs that cost nothing until the user actually asks for them.</em></p><p>I hope you enjoyed reading this article. If you did, I would appreciate if you share it with your peers.</p><p>Cheers! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31284f61e984" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lazy-load-material-dialogs-31284f61e984">Lazy load Material Dialogs</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy-loading reCAPTCHA with Token Aliasing in Angular]]></title>
            <link>https://blog.stackademic.com/lazy-loading-recaptcha-with-token-aliasing-in-angular-866b486c0d7a?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/866b486c0d7a</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[recaptcha]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 07:46:51 GMT</pubDate>
            <atom:updated>2026-01-27T13:08:36.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-0cdvAEGgGpFympw0wkgg.png" /></figure><p>Integrating Google reCAPTCHA into an application is usually straightforward.</p><p>You install a third-party library, provide a site key, inject a service , and you’re done.</p><p>But in real production systems, <strong>integration is rarely the hard part</strong>.</p><p>The real challenge appears when performance meets reality:</p><p><strong>real users, real devices, real networks.</strong></p><h4>The real problem: script size &amp; timing</h4><p>Google’s reCAPTCHA script is <strong>relatively large</strong>.</p><p>Loading it eagerly , as most libraries and examples suggest , can negatively affect:</p><ul><li>initial page load</li><li>time to interactive</li><li>perceived performance on slower devices</li></ul><p>In our case, loading the script upfront caused <strong>visible UI freezes</strong> for some users in QA and production environments, even though everything looked fine locally.</p><p>And that’s the key insight:</p><blockquote><em>Documentation optimizes for correctness , not for user experience.</em></blockquote><p>We didn’t need reCAPTCHA on page load.</p><p>We only needed it <strong>right before the user submits a form</strong>.</p><p>So the goal became clear:</p><p><strong>Load the reCAPTCHA script only when it’s actually needed.</strong></p><h3>Lazy-loading reCAPTCHA the right way</h3><p>Instead of relying on a third-party abstraction, we introduced a small internal layer that gave us:</p><ul><li>full control over <em>when</em> the script loads</li><li>a single execution path</li><li>a predictable API for the rest of the app</li></ul><p>At the core is an abstract service and a concrete Google implementation.</p><p><strong>Injection token for the site key:</strong></p><pre>export const RECAPTCHA_KEY = new InjectionToken&lt;string&gt;(&#39;RECAPTCHA_KEY&#39;);<br><br>export function provideGrecaptcha(siteKey: string) {<br>  return [<br>    { provide: RECAPTCHA_KEY, useValue: siteKey },<br>    { provide: RecaptchaService, useClass: GoogleRecaptchaService }<br>  ];<br>}</pre><p>This keeps configuration explicit and testable.</p><p><strong>Abstract contract:</strong></p><pre>@Injectable()<br>export abstract class RecaptchaService {<br>  public abstract execute(action?: string): Promise&lt;string&gt;;<br>  public abstract loadScript(): Promise&lt;void&gt;;<br>}</pre><p>The rest of the application depends on <strong>intent</strong>, not implementation.</p><p><strong>Google reCAPTCHA implementation:</strong></p><pre>declare const grecaptcha: {<br>  ready: (callback: () =&gt; void) =&gt; void;<br>  execute: (siteKey: string, options: { action: string }) =&gt; Promise&lt;string&gt;;<br>};<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class GoogleRecaptchaService extends RecaptchaService {<br>  private document = inject&lt;Document&gt;(DOCUMENT);<br>  private siteKey = inject(RECAPTCHA_KEY);<br>  private renderer = inject(RendererFactory2).createRenderer(null, null);<br>  private isBrowser = isPlatformBrowser(inject(PLATFORM_ID));<br><br>  private scriptLoaded: Promise&lt;void&gt; | null = null;<br><br>  execute(action: string = &#39;submit&#39;): Promise&lt;string&gt; {<br>    if (!this.isBrowser) {<br>      return Promise.resolve(&#39;&#39;);<br>    }<br><br>    return this.loadScript().then(() =&gt; {<br>      return new Promise((resolve, reject) =&gt; {<br>        grecaptcha.ready(() =&gt; {<br>          grecaptcha.execute(this.siteKey, { action }).then(resolve, reject);<br>        });<br>      });<br>    });<br>  }<br><br>  loadScript(): Promise&lt;void&gt; {<br>    if (!this.scriptLoaded) {<br>      this.scriptLoaded = new Promise((resolve, reject) =&gt; {<br>        const script = this.renderer.createElement(&#39;script&#39;);<br>        script.src = `https://www.google.com/recaptcha/api.js?render=${this.siteKey}`;<br>        script.async = true;<br>        script.defer = true;<br>        script.onload = () =&gt; resolve();<br>        script.onerror = reject;<br>        this.renderer.appendChild(this.document.head, script);<br>      });<br>    }<br><br>    return this.scriptLoaded;<br>  }<br>}</pre><p>At this point, the implementation is solid, but we can improve <strong>dependency access</strong>.</p><p>Instead of eagerly injecting the concrete implementation everywhere, we can use <strong>token aliasing</strong> and resolve the service only when needed.</p><h3>Token aliasing in practice</h3><p>Angular allows us to tell the DI system:</p><blockquote><em>“Whenever someone asks for RecaptchaService, give them the actual implementation.”</em></blockquote><p>Then, in the component:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `&lt;button (click)=&quot;executeRecaptcha()&quot;&gt;Submit&lt;/button&gt;`<br>})<br>export class App {<br>  private readonly injector = inject(Injector);<br><br>  async executeRecaptcha() {<br>    const recaptcha = this.injector.get(RecaptchaService);<br>    console.log(await recaptcha.execute());<br>  }<br>}</pre><h3>Why this matters</h3><ul><li>The service is resolved <strong>only when the user acts</strong></li><li>No unnecessary work during component initialization</li><li>Cleaner mental model: <em>security logic happens at intent time</em></li></ul><p>This pattern becomes especially powerful when:</p><ul><li>features are conditionally enabled</li><li>scripts are heavy</li><li>performance budgets matter</li></ul><h3>Final thoughts</h3><p>The biggest takeaway isn’t about reCAPTCHA.</p><p>It’s about mindset:</p><ul><li>Don’t load heavy third-party code unless you truly need it</li><li>Don’t let documentation dictate UX</li><li>Use Angular’s DI system as a <strong>performance tool</strong>, not just a wiring mechanism</li></ul><p><strong>Token aliasing + lazy loading</strong> gives you control, predictability, and better real-world performance , exactly what you want in security-sensitive flows.</p><p>P.S. This solution would work with existing Angular libraries such as <em>ng-recaptcha</em> &amp; <em>ng-recaptcha2</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866b486c0d7a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lazy-loading-recaptcha-with-token-aliasing-in-angular-866b486c0d7a">Lazy-loading reCAPTCHA with Token Aliasing in Angular</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending the Angular Router with Dependency Injection]]></title>
            <link>https://blog.stackademic.com/extending-the-angular-router-with-dependency-injection-d684fd307f98?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d684fd307f98</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 19:09:30 GMT</pubDate>
            <atom:updated>2026-02-07T12:38:12.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ec4s9sCgkJK2rY3p-14Krw.png" /></figure><p>Recently, I had the pleasure of working on a charity project — more details on that soon, once we’re ready to share it publicly 🙂</p><p>For now, let me introduce the team behind it.</p><p>We are <a href="https://pushserbia.com/"><strong>Push Serbia</strong></a> — an open-source engineering community from Serbia focused on collaboration, knowledge sharing, and building tools that help developers learn, grow, and connect.</p><p>I also want to give a special thanks to <a href="https://www.linkedin.com/in/dusanperisic/"><strong>Dušan Perišić</strong></a> for pushing me into this challenge.</p><p><em>Pun intended.</em></p><h3>What Problem Are We Solving?</h3><p>Angular has evolved tremendously over the last few releases.</p><p>With <strong>Server-Side Rendering (SSR)</strong> now mature and first-class, Angular has become an excellent choice for building <strong>SEO-friendly applications</strong>.</p><p>For localization, we integrated <strong>ngx-translate</strong> to handle translations in a clean and familiar way. That part worked great.</p><p>However, SEO introduces an additional requirement.</p><p>We needed <strong>localized, crawlable URLs</strong> — meaning routes like:</p><pre>/en<br>/sr</pre><p>At first glance, this sounds simple.</p><p>But once you start wiring routing, localization, guards, initial navigation, and SSR together, things get interesting.</p><p>That’s where the <strong>Angular Router</strong> — and more importantly, <strong>Dependency Injection</strong> — comes into play.</p><h3>Where This Article Is Going</h3><p>In this article, we’ll explore:</p><ul><li>why localization-aware routing matters for SEO</li><li>where the default Angular Router falls short</li><li>how to <strong>extend routing behavior using DI</strong></li><li>how to keep the solution clean, testable, and SSR-friendly</li></ul><p>Let’s dive in.</p><h3>Why Localization-Aware Routing Matters for SEO</h3><p>Search engines index <strong>URLs</strong>, not UI state.</p><p>If language is not reflected in the URL, crawlers can’t properly understand, rank, or target your content per locale.</p><p>Search engines assume:</p><pre>/en/about<br>/sr/about</pre><p>are <strong>two different documents</strong> intended for <strong>two different audiences</strong>.</p><p>If instead you do this:</p><pre>/about   // language decided by JS, cookies, or headers</pre><p>then from a crawler’s perspective:</p><ul><li>there is only one page</li><li>language switching is opaque</li><li>SEO signals get mixed</li><li>indexing becomes unreliable</li></ul><p>👉 <strong>Result:</strong> weaker rankings and incorrect language targeting.</p><h3>Step 1: Initialize Language Early</h3><p>The first thing we need is to initialize the language used by <em>ngx-translate</em>.</p><p>We do this using an <strong>App Initializer</strong>, ensuring the correct language is set <strong>before routing and rendering</strong>, which is especially important for SSR.</p><p><strong>App Config:</strong></p><pre>import { ApplicationConfig, provideAppInitializer } from &#39;@angular/core&#39;;<br>import { languageInitializer } from &#39;./core/language&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideTranslateService({<br>      lang: &#39;en&#39;,<br>      fallbackLang: &#39;en&#39;,<br>      loader: provideTranslateHttpLoader({<br>        prefix: &#39;/i18n/&#39;,<br>        suffix: &#39;.json&#39;<br>      })<br>    }),<br>    provideAppInitializer(() =&gt; languageInitializer())<br>  ],<br>};</pre><p><strong>languageInitializer:</strong></p><pre>export type Language = &#39;sr&#39; | &#39;en&#39;;<br><br>export const SUPPORTED_LANGUAGES = new InjectionToken&lt;Language[]&gt;(<br>  &#39;SUPPORTED_LANGUAGES&#39;,<br>  {<br>    providedIn: &#39;root&#39;,<br>    factory: () =&gt; [&#39;en&#39;, &#39;sr&#39;] as const,<br>  }<br>);<br><br>export function languageInitializer() {<br>  const translate = inject(TranslateService);<br>  const platformLocation = inject(PlatformLocation);<br>  const supportedLanguages = inject(SUPPORTED_LANGUAGES);<br><br>  const path = platformLocation.pathname;<br>  const segments = path.split(&#39;/&#39;).filter(Boolean);<br>  const language = segments[0] || &#39;en&#39;;<br><br>  if (supportedLanguages.includes(language as Language)) {<br>    translate.use(language);<br>  }<br>}</pre><p>This ensures the correct language is active <strong>based on the URL</strong>, before anything else happens.</p><h3>Step 2: Language-Aware Routes</h3><p>Now we define our routes with a dynamic <em>:language</em> segment.</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { canMatchLanguageRoute } from &#39;./core/language&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;:language&#39;,<br>    canMatch: [canMatchLanguageRoute],<br>    children: [<br>      {<br>        path: &#39;&#39;,<br>        pathMatch: &#39;full&#39;,<br>        loadComponent: () =&gt;<br>          import(&#39;./features/home/home&#39;).then(m =&gt; m.Home),<br>      },<br>      {<br>        path: &#39;about&#39;,<br>        loadComponent: () =&gt;<br>          import(&#39;./features/about/about&#39;).then(m =&gt; m.About),<br>      },<br>    ],<br>  },<br>];</pre><p><strong>Guarding Unsupported Languages:</strong></p><pre>export function canMatchLanguageRoute(<br>  _route: Route,<br>  segments: UrlSegment[]<br>): boolean {<br>  const supportedLanguages = inject(SUPPORTED_LANGUAGES);<br>  const router = inject(Router);<br><br>  const language = segments[0]?.path as Language || &#39;en&#39;;<br><br>  if (!supportedLanguages.includes(language)) {<br>    router.navigateByUrl(&#39;/en&#39;);<br>    return false;<br>  }<br><br>  return true;<br>}</pre><p>This prevents users and crawlers from accessing unsupported language routes while keeping the route definition clean.</p><h3>Step 3: Extending the Router with DI</h3><p>Now comes the interesting part.</p><p>We wanted <strong>every navigation</strong> — including router.navigateByUrl() and routerLink — to automatically include the current language <strong>without manually passing it around</strong>.</p><p>Instead of sprinkling language logic throughout the app, we <strong>extended Angular’s Router itself</strong>.</p><p><strong>LanguageRouter</strong></p><pre>@Injectable()<br>class LanguageRouter extends Router {<br>  private readonly translate = inject(TranslateService);<br>  private readonly supportedLanguages = inject&lt;Language[]&gt;(SUPPORTED_LANGUAGES);<br><br>  override navigateByUrl(<br>    url: string | UrlTree,<br>    extras?: NavigationBehaviorOptions,<br>  ): Promise&lt;boolean&gt; {<br>    const currentLang = this.translate.getCurrentLang() || &#39;en&#39;;<br>    const urlString = typeof url === &#39;string&#39; ? url : this.serializeUrl(url);<br><br>    const { path, query, fragment } = this.parseUrlParts(urlString);<br>    const finalPath = this.addLanguagePrefix(path, currentLang);<br>    const finalUrlString = this.reconstructUrl(finalPath, query, fragment);<br><br>    const finalUrl: string | UrlTree =<br>      typeof url === &#39;string&#39; ? finalUrlString : this.parseUrl(finalUrlString);<br><br>    const currentUrl = this.url;<br>    const finalUrlSerialized =<br>      typeof finalUrl === &#39;string&#39; ? finalUrl : this.serializeUrl(finalUrl);<br><br>    if (currentUrl === finalUrlSerialized) {<br>      return Promise.resolve(false);<br>    }<br><br>    return super.navigateByUrl(finalUrl, extras);<br>  }<br><br>  private isLanguagePath(segment: string): boolean {<br>    return this.supportedLanguages.includes(segment as Language);<br>  }<br><br>  private parseUrlParts(urlString: string): { path: string; query?: string; fragment?: string } {<br>    const questionMarkIndex = urlString.indexOf(&#39;?&#39;);<br>    const hashIndex = urlString.indexOf(&#39;#&#39;);<br><br>    let path: string;<br>    let query: string | undefined;<br>    let fragment: string | undefined;<br><br>    if (questionMarkIndex !== -1) {<br>      path = urlString.substring(0, questionMarkIndex);<br>      const afterQuestion = urlString.substring(questionMarkIndex + 1);<br>      if (hashIndex !== -1 &amp;&amp; hashIndex &gt; questionMarkIndex) {<br>        query = urlString.substring(questionMarkIndex + 1, hashIndex);<br>        fragment = urlString.substring(hashIndex + 1);<br>      } else {<br>        query = afterQuestion;<br>      }<br>    } else if (hashIndex !== -1) {<br>      path = urlString.substring(0, hashIndex);<br>      fragment = urlString.substring(hashIndex + 1);<br>    } else {<br>      path = urlString;<br>    }<br><br>    return { path, query, fragment };<br>  }<br><br>  private addLanguagePrefix(path: string, language: string): string {<br>    const pathSegments = path.split(&#39;/&#39;).filter((s) =&gt; s.length &gt; 0);<br>    const firstSegment = pathSegments[0];<br>    const hasLanguagePrefix = firstSegment &amp;&amp; this.isLanguagePath(firstSegment);<br><br>    if (hasLanguagePrefix) {<br>      if (firstSegment === language) {<br>        return path;<br>      }<br>      pathSegments[0] = language;<br>      return &#39;/&#39; + pathSegments.join(&#39;/&#39;);<br>    }<br><br>    const trimmedPath = path.startsWith(&#39;/&#39;) ? path.substring(1) : path;<br>    return `/${language}${trimmedPath ? &#39;/&#39; + trimmedPath : &#39;&#39;}`;<br>  }<br><br>  private reconstructUrl(path: string, query?: string, fragment?: string): string {<br>    let url = path;<br>    if (query) {<br>      url += &#39;?&#39; + query;<br>    }<br>    if (fragment) {<br>      url += &#39;#&#39; + fragment;<br>    }<br>    return url;<br>  }<br>}</pre><h3>Step 4: Override the Router via DI</h3><p>Now we tell Angular to use our router instead of the default one.</p><pre>export function provideLanguageRouter(): Provider[] {<br>  return [{ provide: Router, useClass: LanguageRouter }];<br>}</pre><p>And register it <strong>after</strong> provideRouter:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    // ...<br>    provideAppInitializer(() =&gt; languageInitializer()),<br>    provideRouter(routes),<br>    provideClientHydration(withEventReplay()),<br>    provideLanguageRouter(), // must come after provideRouter<br>  ],<br>};</pre><h3>The Result</h3><p>Now:</p><ul><li>every routerLink</li><li>every navigateByUrl</li><li>every programmatic navigation</li></ul><p><strong>automatically respects the active language</strong>.</p><p>No repetitive code.</p><p>No manual prefixing.</p><p>No leaking localization logic into components.</p><h3>Final Thoughts</h3><p>This approach keeps:</p><ul><li>routing declarative</li><li>localization explicit</li><li>SEO solid</li><li>SSR happy</li></ul><p>And most importantly, it uses Angular’s <strong>Dependency Injection system the way it was meant to be used</strong> — extending behavior without fighting the framework.</p><p>If you’re building localized, SEO-friendly Angular apps, this pattern scales surprisingly well.</p><p>Happy routing! 🚀</p><p>P.S. <strong>Special thanks to </strong><a href="https://medium.com/@ekstremac"><strong>Dušan Perišić</strong></a> for pushing me into this challenge.</p><p>If you’re interested in Angular, architecture, or clean problem-solving approaches — I highly recommend following him.</p><p>👉 Follow him on <a href="https://medium.com/@ekstremac">Medium</a>.</p><p>👉 Follow <a href="https://www.linkedin.com/in/dusanperisic/"><strong>Dušan Perišić</strong></a> for more great Angular insights 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d684fd307f98" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/extending-the-angular-router-with-dependency-injection-d684fd307f98">Extending the Angular Router with Dependency Injection</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Form Field with Signal Forms]]></title>
            <link>https://blog.stackademic.com/custom-form-field-with-signal-forms-8a9044c27730?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9044c27730</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-signals]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 09:52:21 GMT</pubDate>
            <atom:updated>2025-12-07T18:08:14.096Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>For years we were relying on the Control Value Accessor.</em></blockquote><blockquote><em>With Signal Forms comes the new interface we need to implement.</em></blockquote><h3>From ControlValueAccessor to FormValueControl</h3><p>With classic Reactive Forms, if you wanted a custom form field (date picker, rich text editor, dropdown, etc.), you had to:</p><ul><li>implement ControlValueAccessor</li><li>register it with NG_VALUE_ACCESSOR</li><li>manually implement writeValue, registerOnChange, setDisabledState, etc.</li></ul><p>With <strong>Signal Forms</strong>, the contract moves to <strong>interfaces</strong> instead of opaque callbacks:</p><ul><li>FormUiControl — optional UI/status inputs (errors, disabled, touched, etc.)</li><li>FormValueControl&lt;TValue&gt; — the main contract for controls that edit a value</li></ul><p>If your component implements FormValueControl&lt;TValue&gt;, the <strong>Field directive</strong> knows how to bind a field to it.</p><h3>What these interfaces really mean</h3><h3>FormUiControl</h3><p>This is a <em>“nice to have”</em> set of inputs. Each property is:</p><ul><li><strong>optional</strong></li><li>an InputSignal&lt;…&gt; (or similar)</li><li>automatically bound by Field if present</li></ul><p>Examples:</p><ul><li>errors?: InputSignal&lt;ValidationError[]&gt;</li></ul><p>→ If you implement it, Field will push validation errors into your component.</p><ul><li>disabled?: InputSignal&lt;boolean&gt;</li></ul><p>→ If implemented, your component will receive true/false based on field state.</p><ul><li>touched?, dirty?, invalid?, pending?, required?, min, max, minLength, maxLength, pattern, etc.</li></ul><p>→ All these make it possible to build super smart custom components that fully reflect field state without you manually wiring things up.</p><p>You can implement <strong>none</strong>, <strong>some</strong>, or <strong>all</strong> of these. Only value is required — and that’s on the next interface.</p><h3>FormValueControl&lt;TValue&gt;</h3><p>This is the <strong>core contract</strong> for a “normal” custom field:</p><pre>interface FormValueControl&lt;TValue&gt; extends FormUiControl {<br>  readonly value: ModelSignal&lt;TValue&gt;;<br>  readonly checked?: undefined;<br>}</pre><p>Key points:</p><ul><li>value: ModelSignal&lt;TValue&gt; is <strong>required</strong></li></ul><p>→ This is the two-way binding between your component and the form.</p><ul><li>checked?: undefined is explicitly disallowed here</li></ul><p>→ That’s reserved for a different contract (checkbox style components).</p><p>So:</p><blockquote><strong><em>If your component has a value model signal, it can be used with [field].</em></strong></blockquote><p>No writeValue, no registerOnChange, no providers. Just a model signal.</p><h3>Minimal example: Custom input with Signal Forms</h3><p>Imagine a simple custom input component:</p><pre>import { Component, model, input } from &#39;@angular/core&#39;;<br>import { Field } from &#39;@angular/forms/signals&#39;;<br>import type { FormValueControl } from &#39;@angular/forms/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-fancy-input&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;label class=&quot;flex flex-col gap-1&quot;&gt;<br>      &lt;span class=&quot;text-sm font-medium&quot;&gt;Fancy input&lt;/span&gt;<br>      &lt;input<br>        class=&quot;border rounded px-3 py-2&quot;<br>        [value]=&quot;value()&quot;<br>        (input)=&quot;value.set($any($event.target).value)&quot;<br>        [disabled]=&quot;disabled() ?? false&quot;<br>      /&gt;<br>    &lt;/label&gt;<br>  `,<br>})<br>export class FancyInputComponent implements FormValueControl&lt;string&gt; {<br>  // required by FormValueControl<br>  readonly value = model&lt;string&gt;(&#39;&#39;);<br><br>  // optional, from FormUiControl — Field will bind them if present<br>  readonly errors = input&lt;ReadonlyArray&lt;{ message: string }&gt; | undefined&gt;();<br>  readonly disabled = input&lt;boolean&gt;();<br>  readonly invalid = input&lt;boolean&gt;();<br>}</pre><p>Then you can use it in a Signal Form like this:</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { form, Field } from &#39;@angular/forms/signals&#39;;<br>import { FancyInputComponent } from &#39;./fancy-input.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [Field, FancyInputComponent],<br>  template: `<br>    &lt;form&gt;<br>      &lt;app-fancy-input [field]=&quot;form.name&quot;&gt;&lt;/app-fancy-input&gt;<br>    &lt;/form&gt;<br>  `,<br>})<br>export class AppComponent {<br>  private readonly model = signal({ name: &#39;&#39; });<br><br>  protected readonly form = form(this.model);<br>}</pre><p>That’s it. No CVA, no NG_VALUE_ACCESSOR.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9044c27730" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/custom-form-field-with-signal-forms-8a9044c27730">Custom Form Field with Signal Forms</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signal Forms with Resource API is Magic]]></title>
            <link>https://blog.stackademic.com/signal-forms-with-resource-api-is-magic-cf4c0d249902?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf4c0d249902</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular-signals]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 14:37:14 GMT</pubDate>
            <atom:updated>2025-12-01T20:38:28.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxTESu_lpp6MG9D_hIbSWA.png" /></figure><p>With the newest version of Angular comes one of the most impactful changes to its reactive ecosystem: <strong>Signal Forms</strong> — a modern, signal-driven way to handle web forms in Angular.</p><p>For years, we relied on <strong>Reactive Forms</strong>, a powerful but sometimes verbose API that required a lot of boilerplate:</p><ul><li>FormGroup, FormControl, FormArray</li><li>manual subscriptions and cleanup</li><li>patchValue / setValue calls</li><li>imperative RxJS pipelines just to connect form values to HTTP calls</li></ul><p>Reactive Forms served us well, but as Angular evolved into a <strong>signal-first</strong> framework, the gap between the synchronous world of signals and the asynchronous mechanics of Reactive Forms became more visible.</p><p><strong>Signal Forms</strong> close that gap on the <em>form state</em> side.</p><p>And when you combine them with the <strong>Resource API</strong>, you also get a clean, declarative bridge between:</p><blockquote><em>form → signals → async HTTP → signal state again.</em></blockquote><p>Before we get to the “magic” version, let’s look at a typical real-world example using classic Reactive Forms.</p><h3>🛒 Real-World Example: Product Search Form (Reactive Forms)</h3><p>Imagine you’re building an e-commerce platform that supports searching and filtering products based on different criteria.</p><p>To keep things focused, we’ll start with a single <strong>search input</strong> field that queries a public API.</p><p>The API response looks like this:</p><pre>export interface ProductsResponse {<br>  products: unknown[]; // Product[]<br>  total: number;<br>  skip: number;<br>  limit: number;<br>}</pre><p>A straightforward Reactive Form implementation might look like this:</p><pre>import { Component, DestroyRef, OnInit, inject, signal } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { FormControl, FormGroup, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br>import { debounceTime, map, startWith, switchMap } from &#39;rxjs/operators&#39;;<br>import { takeUntilDestroyed } from &#39;@angular/core/rxjs-interop&#39;;<br>import { NgFor, JsonPipe } from &#39;@angular/common&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, NgFor, JsonPipe],<br>  styleUrl: &#39;./app.css&#39;,<br>  template: `<br>    &lt;main&gt;<br>      &lt;form [formGroup]=&quot;form&quot;&gt;<br>        &lt;div&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            formControlName=&quot;search&quot;<br>            placeholder=&quot;Search for products...&quot;<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/form&gt;<br><br>      &lt;!-- Products list --&gt;<br>      &lt;ul&gt;<br>        &lt;li *ngFor=&quot;let product of products()&quot;&gt;<br>          {{ product | json }}<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/main&gt;<br>  `,<br>})<br>export class App implements OnInit {<br>  private readonly http = inject(HttpClient);<br>  private readonly destroyRef = inject(DestroyRef);<br><br>  protected readonly form = new FormGroup({<br>    search: new FormControl(&#39;&#39;),<br>  });<br><br>  protected readonly products = signal&lt;unknown[]&gt;([]);<br><br>  ngOnInit(): void {<br>    this.form.valueChanges<br>      .pipe(<br>        startWith(this.form.value),<br>        debounceTime(300),<br>        map(value =&gt; ({ q: value.search ?? &#39;&#39; })),<br>        switchMap(params =&gt;<br>          this.http.get&lt;ProductsResponse&gt;(<br>            &#39;https://dummyjson.com/products/search&#39;,<br>            { params },<br>          ),<br>        ),<br>        takeUntilDestroyed(this.destroyRef),<br>      )<br>      .subscribe({<br>        next: data =&gt; {<br>          this.products.set(data.products);<br>        },<br>        error: err =&gt; console.error(&#39;Error fetching products:&#39;, err),<br>      });<br>  }<br>}</pre><h3>😅 What’s “wrong” with this picture?</h3><p>This works — but notice how much is going on just to wire a single search field to an HTTP call:</p><ul><li>The form lives in <strong>Reactive Forms land</strong> (FormGroup, FormControl).</li><li>The search logic is implemented as an <strong>imperative RxJS pipeline</strong> in ngOnInit.</li><li>We manually:</li></ul><ol><li>debounce input,</li><li>build query params,</li><li>switch to a new HTTP call,</li><li>subscribe,</li><li>and push the result into a <strong>signal</strong> (products).</li></ol><ul><li>We need takeUntilDestroyed(this.destroyRef) to avoid leaks.</li></ul><p>So we end up with three mental models in one component:</p><ol><li><strong>Reactive Forms API</strong> for form state</li><li><strong>RxJS</strong> for async work and side-effects</li><li><strong>Signals</strong> for view state (products)</li></ol><p>This is exactly the kind of glue code that <strong>Signal Forms + Resource API</strong> are designed to simplify.</p><h3>🔁 Reactive Form to Signal Form</h3><p>Migrating a Reactive Form to a Signal Form can be done in a few clear steps:</p><ol><li>Remove <em>ReactiveFormsModule</em> from imports.</li><li>Remove the <em>[formGroup] </em>directive from the &lt;form&gt; element.</li><li>Move your form model into a signal-backed object.</li><li>Use the form function from @angular/forms/signals to build a Signal Form out of that model.</li><li>Use the Field directive from @angular/forms/signals to bind your inputs.</li></ol><p>In other words:</p><pre>import { Field } from &#39;@angular/forms/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [Field, JsonPipe, NgFor],<br>  styleUrl: &#39;./app.css&#39;,<br>  template: `<br>    &lt;main&gt;<br>      &lt;form&gt;<br>        &lt;div&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            [field]=&quot;form.search&quot;<br>            placeholder=&quot;Search for products...&quot;<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/form&gt;<br><br>      &lt;!-- Products list --&gt;<br>      &lt;ul&gt;<br>        &lt;li *ngFor=&quot;let product of products()&quot;&gt;<br>          {{ product | json }}<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/main&gt;<br>  `,<br>})<br>export class App {<br>  private readonly http = inject(HttpClient);<br><br>  private readonly model = signal&lt;{ search: string; }&gt;({<br>    search: &#39;&#39;<br>  });<br><br>  protected readonly form = form&lt;{ search: string; }&gt;(this.model);<br>  ...</pre><p>At this point, the refactoring is clean and minimal.</p><p><strong>But now comes the fun part</strong>:</p><p>👉 <em>How do we replace the RxJS pipeline and subscription with something that fits nicely into Angular’s signal model?</em></p><h3>⚡ Resource API to the Rescue</h3><p>We want our Products API to react to form value changes.</p><p>Yes, we <em>could</em> do something like toObservable(this.model) and rebuild the same RxJS pipeline. It would work… but:</p><ul><li>Where do we keep <strong>loading</strong> state?</li><li>Where do we expose <strong>errors</strong>?</li><li>How do we <strong>cancel in-flight requests</strong> when the search changes quickly?</li><li>How do we stay inside the <strong>signal graph</strong> instead of bolting RxJS on the side?</li></ul><p>But it quickly gets messy when we also want:</p><ul><li>loading state</li><li>error state</li><li>cache or retry logic</li><li>cancellable requests</li><li>reactivity based on dependencies</li></ul><p>Signals shine with <strong>purity</strong> and <strong>synchronous state</strong>, but real applications aren’t purely synchronous — we fetch, mutate, poll, and stream.</p><p>The <strong>Resource API</strong> gives us a unified, declarative way to:</p><ul><li>bind asynchronous data sources to signals</li><li>track loading, success, and error states</li><li>re-run automatically when dependencies change</li><li>cancel previous in-flight requests</li><li>stay inside Angular’s reactive graph</li></ul><p>No RxJS pipeline, no ngOnInit, no manual cleanup.</p><blockquote><em>Angular gives you two flavors of Resource:</em></blockquote><blockquote>resource for async/Promise-based loaders</blockquote><blockquote>rxResource from @angular/core/rxjs-interop for Observable-based streams (like HttpClient)</blockquote><blockquote><em>In this article we’ll focus on rxResource, since HttpClient returns Observables.</em></blockquote><p>Creating an RxResource is simple — just call the rxResource function:</p><pre>import { rxResource } from &#39;@angular/core/rxjs-interop&#39;;<br><br>protected readonly products = rxResource&lt;ProductsResponse, { search: string }&gt;({<br>  params: () =&gt; this.form().value(),<br>  stream: ({ params }) =&gt; {<br>    return this.http.get&lt;ProductsResponse&gt;(<br>      &#39;https://dummyjson.com/products/search&#39;,<br>      { params: { q: params.search } },<br>    );<br>  },<br>});</pre><p>What’s happening here?</p><ul><li>params: () =&gt; this.form().value()</li></ul><ol><li>The Resource tracks the <strong>Signal Form value</strong> as a dependency.</li><li>Whenever the form value changes the resource <strong>re-runs</strong>.</li></ol><ul><li>stream: ({ params }) =&gt; this.http.get(…</li></ul><ol><li>For each new set of params, we return an <strong>Observable</strong> (our HTTP call).</li><li>rxResource subscribes for us, handles cancellation when params change, and updates its internal <strong>signal state</strong>.</li></ol><p>The result is a single, declarative resource we can use in the template as:</p><ul><li>products.value() — current data:</li><li>products.loading() — loading flag</li><li>products.error() — error object</li></ul><p>All without writing a single subscribe().</p><h3>✨ The “Magic” Version: Signal Form + RxResource</h3><p>Here’s the full version using:</p><ul><li><strong>Signal Forms</strong> for the search field</li><li><strong>debounce</strong> for UX</li><li><strong>RxResource</strong> for the HTTP call + loading/error/value states</li><li>Tailwind just to make the demo look nice</li></ul><pre>import { JsonPipe } from &#39;@angular/common&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Component, effect, inject, signal } from &#39;@angular/core&#39;;<br>import { rxResource } from &#39;@angular/core/rxjs-interop&#39;;<br>import { debounce, Field, form, submit } from &#39;@angular/forms/signals&#39;;<br><br>export interface ProductsSearchQuery {<br>  search: string;<br>}<br><br>export interface ProductsResponse {<br>  products: unknown[];<br>  total: number;<br>  skip: number;<br>  limit: number;<br>}<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [Field, JsonPipe],<br>  styleUrl: &#39;./app.css&#39;,<br>  template: `<br>    &lt;div class=&quot;min-h-screen bg-linear-to-br from-blue-50 to-indigo-100 py-12 px-4 sm:px-6 lg:px-8&quot;&gt;<br>      &lt;div class=&quot;max-w-4xl mx-auto&quot;&gt;<br>        &lt;h1 class=&quot;text-4xl font-bold text-center text-gray-900 mb-8&quot;&gt;<br>          {{ title() }}<br>        &lt;/h1&gt;<br><br>        &lt;!-- Form section --&gt;<br>        &lt;section class=&quot;bg-white rounded-lg shadow-lg p-6 mb-8&quot;&gt;<br>          &lt;h2 class=&quot;text-2xl font-semibold text-gray-800 mb-4 flex items-center&quot;&gt;<br>            &lt;svg class=&quot;w-6 h-6 mr-2 text-indigo-600&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>              &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M5 13l4 4L19 7&quot; /&gt;<br>            &lt;/svg&gt;<br>            Product Search Form<br>          &lt;/h2&gt;<br><br>          &lt;p class=&quot;text-gray-600 mb-4&quot;&gt;<br>            Type in the search box below to find products.<br>            The search will be triggered 300ms after you stop typing.<br>          &lt;/p&gt;<br><br>          &lt;form (submit)=&quot;formSubmit($event)&quot;&gt;<br>            &lt;div class=&quot;relative mb-4&quot;&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                [field]=&quot;form.search&quot;<br>                placeholder=&quot;Search for products...&quot;<br>                class=&quot;w-full px-6 py-4 text-lg border-2 border-gray-300 rounded-lg shadow-sm<br>                       focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent<br>                       transition duration-200&quot;<br>              /&gt;<br><br>              &lt;svg<br>                class=&quot;absolute right-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400&quot;<br>                fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;<br>              &gt;<br>                &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot;<br>                      d=&quot;M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z&quot; /&gt;<br>              &lt;/svg&gt;<br>            &lt;/div&gt;<br><br>            @for (error of form.search().errors(); track error.message) {<br>              &lt;div class=&quot;text-sm text-red-600 flex items-center gap-1 m-2&quot;&gt;<br>                &lt;svg class=&quot;w-4 h-4 text-red-500&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>                  &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot;<br>                        d=&quot;M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z&quot; /&gt;<br>                &lt;/svg&gt;<br>                {{ error.message }}<br>              &lt;/div&gt;<br>            }<br><br>            &lt;button<br>              class=&quot;w-full sm:w-auto px-8 py-3 bg-indigo-600 text-white text-base font-semibold rounded-lg<br>                     shadow-md hover:bg-indigo-700 hover:shadow-lg focus:outline-none focus:ring-2<br>                     focus:ring-indigo-500 focus:ring-offset-2 active:scale-95<br>                     transition-all duration-200 flex items-center justify-center gap-2&quot;<br>              type=&quot;submit&quot;<br>              [disabled]=&quot;form().submitting()&quot;<br>            &gt;<br>              &lt;svg class=&quot;w-5 h-5&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>                &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot;<br>                      d=&quot;M5 13l4 4L19 7&quot; /&gt;<br>              &lt;/svg&gt;<br>              Submit Search<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/section&gt;<br><br>        &lt;!-- Results section --&gt;<br>        &lt;section class=&quot;bg-white rounded-lg shadow-lg p-6&quot;&gt;<br>          &lt;h2 class=&quot;text-2xl font-semibold text-gray-800 mb-4 flex items-center&quot;&gt;<br>            &lt;svg class=&quot;w-6 h-6 mr-2 text-indigo-600&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>              &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot;<br>                    d=&quot;M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2&quot; /&gt;<br>            &lt;/svg&gt;<br>            Products Search Result<br>          &lt;/h2&gt;<br><br>          @if (products.hasValue()) {<br>            &lt;div class=&quot;bg-gray-50 rounded-lg p-4 overflow-auto max-h-96&quot;&gt;<br>              &lt;pre class=&quot;text-sm text-gray-700 whitespace-pre-wrap&quot;&gt;<br>{{ products.value() | json }}<br>              &lt;/pre&gt;<br>            &lt;/div&gt;<br>          }<br>          @else {<br>            @if (products.isLoading()) {<br>              &lt;p class=&quot;text-gray-500&quot;&gt;Loading products...&lt;/p&gt;<br>            }<br>            @else if (products.error()) {<br>              &lt;div class=&quot;bg-red-50 border border-red-200 rounded-lg p-4 flex items-center justify-between&quot;&gt;<br>                &lt;div class=&quot;flex items-center&quot;&gt;<br>                  &lt;svg class=&quot;w-5 h-5 text-red-500 mr-2&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot;&gt;<br>                    &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot;<br>                          d=&quot;M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z&quot; /&gt;<br>                  &lt;/svg&gt;<br>                  &lt;p class=&quot;text-red-700 font-medium&quot;&gt;Error loading products.&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;button<br>                  class=&quot;ml-4 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700<br>                         focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2<br>                         transition duration-200 font-medium&quot;<br>                  (click)=&quot;products.reload()&quot;<br>                &gt;<br>                  Retry<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            }<br>          }<br>        &lt;/section&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class App {<br>  protected readonly title = signal(&#39;Signal Forms with RxResource&#39;);<br>  private readonly http = inject(HttpClient);<br><br>  private readonly model = signal&lt;ProductsSearchQuery&gt;({<br>    search: &#39;&#39;,<br>  });<br><br>  // 1) Build a Signal Form from the model + debounce<br>  protected readonly form = form&lt;ProductsSearchQuery&gt;(this.model, schema =&gt; {<br>    debounce(schema, 300); // debounce form value changes by 300ms<br>  });<br><br>  // 2) Bind async HTTP to Resource state<br>  protected readonly products = rxResource&lt;ProductsResponse, ProductsSearchQuery&gt;({<br>    params: () =&gt; this.form().value(),<br>    stream: ({ params }) =&gt;<br>      this.http.get&lt;ProductsResponse&gt;(&#39;https://dummyjson.com/products/search&#39;, {<br>        params: { q: params.search },<br>      }),<br>  });<br><br>  // Optional: Debug effects to inspect form and resource status in devtools<br>  readonly #productsStatusEffect = effect(() =&gt; {<br>    console.info(&#39;Products Status:&#39;);<br>    console.table({<br>      status: this.products.status(),<br>      loading: this.products.isLoading(),<br>      hasValue: this.products.hasValue(),<br>      error: this.products.error(),<br>    });<br>  });<br><br>  readonly #formStatusEffect = effect(() =&gt; {<br>    console.info(&#39;Form Status:&#39;);<br>    console.table({<br>      valid: this.form().valid(),<br>      invalid: this.form().invalid(),<br>      pending: this.form().pending(),<br>      disabled: this.form().disabled(),<br>      dirty: this.form().dirty(),<br>      touched: this.form().touched(),<br>      submitting: this.form().submitting(),<br>      errors: this.form().errors(),<br>    });<br>  });<br><br>  protected formSubmit(event: Event): void {<br>    event.preventDefault();<br><br>    submit(this.form, async () =&gt; {<br>      // Just to demo field-level errors:<br>      return [<br>        {<br>          kind: &#39;error&#39;,<br>          field: this.form.search,<br>          message: &#39;Simulated error on search field.&#39;,<br>        },<br>      ];<br>    });<br><br>    console.info(&#39;Form Submitted:&#39;);<br>    console.table(this.form().value());<br>  }<br>}</pre><h3>🧠 What Did We Gain?</h3><p>Compare this with the original Reactive Forms + RxJS version:</p><ul><li>No FormGroup, FormControl, valueChanges, takeUntilDestroyed.</li><li>No manual subscription, no ngOnInit.</li><li>Debounce is declared <strong>at the form level</strong>: debounce(schema, 300).</li><li>rxResource:</li></ul><ol><li>tracks status, isLoading, error, hasValue</li><li>automatically re-runs when params change</li><li>keeps everything in the <strong>signal graph</strong></li></ol><p>Your mental model becomes:</p><ul><li><strong>Signal Form</strong> for synchronous <strong>form state</strong></li><li><strong>RxResource</strong> for asynchronous <strong>data state</strong></li><li>Template just reacts to <strong>signals</strong> and <strong>resource status</strong></li></ul><p>The code reads almost like a description of the UI behavior.</p><h3>⚠️ A Note on Experimental APIs</h3><p>At the time of writing, both:</p><ul><li><strong>Signal Forms</strong>, and</li><li><strong>Resource / RxResource</strong></li></ul><p>are still marked as <strong>experimental / developer-preview</strong> in Angular. They’re already very usable, but small API changes may still happen between versions.</p><p>That said, the <strong>core idea</strong> — connect forms → signals → async resources — is here to stay, and it’s already a huge quality-of-life improvement over the classic setup.</p><h3>✅ When to Reach for Signal Forms + Resource API</h3><p>You’ll feel the most value when:</p><ul><li>Your forms are tightly coupled with <strong>HTTP calls</strong> (searches, filters, autocompletes, wizard steps).</li><li>You want to <strong>avoid glue code</strong> and keep everything inside the signal model.</li><li>You care about:</li></ul><ol><li>loading/error states in the template,</li><li>proper cancellation of in-flight requests,</li><li>keeping your components small and declarative.</li></ol><p>For simple forms that don’t hit APIs, Reactive Forms are still fine.</p><p>But once your UI starts dancing with the backend, <strong>Signal Forms + Resource API</strong> really do feel like magic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf4c0d249902" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/signal-forms-with-resource-api-is-magic-cf4c0d249902">Signal Forms with Resource API is Magic</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Angular: Climbing up the Tree]]></title>
            <link>https://blog.stackademic.com/dependency-injection-in-angular-climbing-up-the-tree-a24018eec12f?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24018eec12f</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 17:43:56 GMT</pubDate>
            <atom:updated>2025-06-30T10:00:56.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IksdG84HWdXue8qopY5z6A.png" /><figcaption>Image is genererated by ChatGPT</figcaption></figure><p>Dependency Injection is a design pattern and core part of <em>Angular’s</em> architecture that allows <em>components</em>, <em>services</em>, and <em>other classes</em> to declare their <em>dependencies</em> and have them automatically <em>provided</em> by the framework, rather than creating them manually.</p><p>Why it matters:</p><ul><li>Decouples classes from their dependencies</li><li>Promotes testability and reusability</li><li>Encourages modular, maintainable architecture</li></ul><h3>Dependency Injection Mechanism</h3><p>Angular allows classes with Angular decorators, such as <em>Components</em>, <em>Directives</em>, <em>Pipes</em>, and <em>Injectables</em>, to configure dependencies via the <strong>Injector Tree</strong>. The <em>Injector Tree</em> is a <em>hierarchical structure of injectors</em> that Angular uses to determine how and where to resolve requested dependencies, starting from the component level and moving up toward global scopes.</p><p>Consider this manually-wired class:</p><pre>class Api {<br>  endpointUrl: string;<br>  http = new HttpClient(new OurHttpHandler());<br>    <br>  constructor(endpointUrl: string) {<br>    this.endpointUrl = endpointUrl;<br>  }<br>}</pre><p>This creates deeply nested object structure:</p><pre>{<br>  endpointUrl: &#39;http://localhost:3333/api&#39;,<br>  http: {<br>    handler: {<br>      handlerProps: {<br>        prop: { ... }<br>      }<br>    },<br>    post(...) { ... }<br>  }<br>}</pre><p>Here’s the <strong>issue</strong>:</p><ul><li><em>HttpClient</em> requires a <em>HttpHandler</em>, which is an <strong>abstract class</strong>, meaning you have to manually implement and instantiate it.</li><li>You’re tightly coupling your class to low-level implementation details.</li><li>As complexity increases, this becomes <strong>hard to maintain, test, and reuse</strong>.</li></ul><p><em>Angular’s DI Mechanism</em> <strong>eliminates manual instantiation</strong> by:</p><ul><li>Managing object creation behind the scenes</li><li>Sharing instances across your app</li><li>Making classes easier to <strong>mock, replace, and test</strong></li></ul><p>Instead of creating an instance of the class like we did above, we can inject the dependency using the inject function, something like this:</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class Api {<br>  private endpointUrl = inject(API_ENDPOINT_URL);<br>  private http = inject(HttpClient);<br>}</pre><p>Rather than creating and passing deeply nested dependencies manually, Angular’s Dependency Injection mechanism allows classes to <strong>declare what they need</strong>, and the <strong>injector tree supplies it</strong>, improving <strong>code clarity, scalability, and testability</strong>.</p><p>Also, we can inject plain objects or variables as well by using the Injection Token like we did for the <em>endpointUrl</em> property. More on that later.</p><h3>Injector Tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQfXD7OxeM9qKryaNAOVVw.png" /></figure><p>When bootstrapping an Angular application using either <em>bootstrapApplication</em> (standalone APIs) or <em>bootstrapModule</em> (NgModules), Angular initializes a <strong>hierarchical Dependency Injection (DI) system</strong>, often referred to as the <strong>Injector Tree</strong>.</p><h4>Null Injector</h4><p>At the very bottom of the <em>injector tree</em> sits the <strong>Null Injector</strong>. It acts as the ultimate fallback. If a requested dependency cannot be found in any other injector, the <em>Null Injector</em> throws a runtime error:</p><pre>NullInjectorError: No provider for &lt;ServiceName&gt;!</pre><p>Its sole responsibility is to <em>fail fast</em> when a dependency resolution hits the bottom with no result.</p><h4>Platform Injector</h4><p>Just above the <em>Null Injector</em> is the <strong>Platform Injector</strong>. It’s created when Angular is first loaded (via <em>platformBrowser</em> or <em>platformBrowserDynamic</em>).</p><p>It contains <strong>global singletons</strong> such as the <em>Angular</em> <em>Compiler</em>, which should be shared across:</p><ul><li>The entire application.</li><li>Multiple Angular apps running on the same page.</li></ul><p>This layer is rarely customized, but it’s essential to support advanced use cases and bootstrapping logic.</p><h4>Root Injector</h4><p>The <strong>Root Injector</strong> is a central part of Angular’s DI hierarchy and is responsible for providing <strong>application-wide singleton services</strong>.</p><ul><li>Services decorated with <a href="http://twitter.com/Injectable"><em>@Injectable</em></a><em>({ providedIn: ‘root’ }) </em>are registered with this injector.</li><li>These services are instantiated once and shared across the entire app, making them efficient and easily accessible.</li></ul><p>Additionally, Angular allows services and injection tokens to be provided through the <strong>Application Configuration object</strong> when using the standalone API:</p><pre>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideHttpClient(),<br>  ]<br>});</pre><p>Now we can use the <em>HttpClient</em> injectable class across the application.</p><h4>Element Injector</h4><p>The <strong>Element Injector</strong> is an instance-level injector created <strong>for each component or directive</strong> in the component tree. It is responsible for resolving dependencies that are <strong>provided locally</strong> at the component or directive level.</p><pre>@Component({<br>  selector: &#39;mk-widget&#39;,<br>  providers: [WidgetService]<br>})<br>export class WidgetComponent {<br>  private readonly widgetService = inject(WidgetService);<br>}</pre><p>By adding a provider (<em>WidgetService</em>) in the providers array of the Component’s decorator, each time the component is created, new instance of the WidgetService is created as well and its lifespan will depend on the lifespan of the component. Also, this instance will be visible in the children’s scope of this component/directive.</p><h3>Services &amp; Injection Tokens</h3><p>Angular’s <strong>Dependency Injection </strong>system is built around <strong>providers</strong>, which associate <strong>tokens</strong> with <strong>dependencies</strong> (usually services). These tokens can either be <strong>classes (types)</strong> or <strong>InjectionToken</strong> instances.</p><p>Whenever we ask for a dependency, we are traversing from <em>Element Injector</em> down to the <em>Null Injector</em> where we can get an error if no provider is found for that dependency.</p><h4>Services</h4><p>A <strong>service</strong> in Angular is typically a class annotated with @Injectable() and designed to encapsulate reusable business logic, state, or utility behavior.</p><p>Services can be <strong>singletons</strong> (if <em>provided</em> in <em>root</em>) or <strong>scoped</strong> (if <em>provided</em> in <em>component</em>, <em>directive</em>, <em>module</em> or <em>route</em>).</p><h4>Injection Tokens</h4><p>In Angular, <strong>Injection Tokens</strong> are a way to tell the Dependency Injection system <strong>what to inject</strong>, especially when you’re not injecting a class.</p><p>They are useful when:</p><ul><li>You’re injecting <strong>primitives</strong> (string, number, boolean)</li><li>You’re injecting a <strong>configuration object</strong></li><li>You have <strong>multiple implementations</strong> of the same interface/type -aliasing</li><li>You want <strong>strong typing</strong> for something that doesn’t have a class</li></ul><p>Let’s consider the already mentioned example for the <em>API Service</em>. Instead of using constructor or other methods to set the endpoint we can inject it as an constant variable.</p><pre>import { InjectionToken } from &#39;@angular/core&#39;;<br><br>export const API_ENDPOINT_URL = new InjectionToken&lt;string&gt;(&#39;API_ENDPOINT_URL&#39;, {<br>  providedIn: &#39;root&#39;,<br>  factory: () =&gt; {<br>    return &#39;https://dummyjson.com&#39;;<br>  },<br>});</pre><p>As you can see, our <em>Injection Token</em> also has the <strong>providedIn: ‘root’</strong> property and with factory function that resolves it’s value, it is ready to use.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class Api {<br>  private readonly endpointUrl = inject(API_ENDPOINT_URL);<br>  private readonly http = inject(HttpClient);<br><br>  post&lt;T, G = any | null&gt;(path: string, body: G) {<br>    return this.http.post&lt;T&gt;(`${this.ENDPOINT}/${path}`, body);<br>  }<br>}</pre><h3>Overriding Providers</h3><p>By default, services provided in root are singletons. But you can override them per <em>Route/Module/Component/Directive</em>:</p><pre>@Component({<br>  selector: &#39;mk-widget&#39;,<br>  providers: [WidgetService]<br>})<br>export class WidgetComponent {...}</pre><p>This allows fine-grained control, useful for:</p><ul><li>Testing</li><li>Feature-specific logic</li><li>Development/debug environments</li></ul><h3>Real World Example</h3><p>Consider we are implementing a <em>Payments</em> service that will act differently if user is paying via <em>PayPal</em> or <em>ApplePay</em> services.</p><p>We could generate a <em>Payments</em> service that will inject our <em>API</em> so we can process our payment whether it is paid via <em>PayPal</em> or <em>ApplePay</em> service.</p><p>Let’s generate a <strong>Payments</strong> service with <em>Angular CLI</em>:</p><pre>ng generate service core/services/payments</pre><p>Also, let’s make it abstract so we never actually work with the Payments Service <em>itself:</em></p><pre>import { inject, Injectable } from &#39;@angular/core&#39;;<br>import { Api } from &#39;./api&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export abstract class Payments {<br>  protected readonly api = inject(Api);<br>  abstract pay: (amount: number) =&gt; number;<br>}</pre><p>The <em>Api</em> service is injected into the abstract <em>Payments</em> class to ensure that all payment implementations have access to the API functionality without duplicating the injection logic in every subclass. This helps keep the subclasses focused solely on their unique behavior and encourages DRY principles.</p><p>Now let’s generate <em>PayPalPayments</em> and <em>ApplePayPayments</em> services.</p><pre>ng generate service core/services/apple-pay-payments<br>ng generate service core/services/pay-pal-payments</pre><p>And implement <em>pay</em> methods:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ApplePayPayments extends Payments {<br>  pay = (amount: number) =&gt; amount + 0.003;<br>}<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class PayPalPayments extends Payments {<br>  pay = (amount: number) =&gt; amount + 0.002;<br>}</pre><p>Let’s imagine that <em>ApplePay</em> and <em>PayPal</em> take 0.003 cents and 0.002 cents respectively when processing the payment. :)</p><p>Now if we try to use the abstract <em>Payments</em> class directly, we would get a <em>compiler error</em>.</p><pre>Type &#39;typeof Payments&#39; is not assignable to type &#39;Provider&#39;.<br>Type &#39;typeof Payments&#39; is not assignable to type &#39;TypeProvider&#39;.<br>Cannot assign an abstract constructor type to a non-abstract constructor type.</pre><p>It is time to override the provider.</p><p>To override an abstract class like Payments, we can register a concrete implementation with Angular&#39;s provider system.</p><p>For example, let’s say you want to use <em>ApplePayPayments</em> in a certain part of your app like <em>ApplePayWidget</em> which extends abstract <em>PaymentWidget </em>class.</p><p>Our <em>PaymentWidget</em> abstract is simple. It injects the <em>Payments</em> service, holds the value of the amount to be paid and has a pay method that <em>alerts</em> the user with the message how much they ended up paying.</p><pre>export abstract class PaymentWidget {<br>  private readonly payments = inject(Payments);<br>  abstract readonly type: &#39;PayPal&#39; | &#39;ApplePay&#39;;<br>  readonly value = signal(0);<br><br>  readonly total = computed(() =&gt; {<br>    const value = this.value();<br>    return value === 0 || value === null ? 0 : this.payments.pay(value);<br>  });<br><br>  pay() {<br>    alert(`You just paid ${this.total()}$ with ${this.type}`);<br>  }<br>}</pre><p>Our actual implementation will be simple. Just assign the <strong>type</strong> value and a very simple UI.</p><pre>@Component({<br>  selector: &#39;app-apple-pay-widget&#39;,<br>  imports: [FormsModule, CurrencyPipe],<br>  providers: [<br>    {<br>      provide: Payments,<br>      useExisting: ApplePayPayments,<br>    },<br>  ],<br>  template: `<br>    &lt;h5&gt;{{type}}&lt;/h5&gt;<br>    &lt;input type=&quot;number&quot; min=&quot;0&quot; [(ngModel)]=&quot;value&quot; /&gt;<br>    &lt;div&gt;Total: &lt;span&gt;{{ total() | currency }}&lt;/span&gt;&lt;/div&gt;<br>    &lt;button (click)=&quot;pay()&quot;&gt;Pay&lt;/button&gt;<br>  `,<br>  templateUrl: &#39;./apple-pay-widget.html&#39;,<br>  styleUrl: &#39;./apple-pay-widget.css&#39;,<br>})<br>export class ApplePayWidget extends PaymentWidget {<br>  readonly type = &#39;ApplePay&#39;;<br>}</pre><h3>Dependency Providers</h3><p>Notice the <em>providers</em> array of the component’s decorator. We have added an element to <strong>provide</strong> <em>Payments</em> service and <strong>use existing class</strong> <em>ApplePayPayments</em> service.</p><h4>useExisting:</h4><p>Use existing means that Dependency Injection will traverse the Injection Tree and look for the <em>already existing instance</em> of the class <em>ApplePayPayments</em> or <em>create new instance </em>if it’s provided. If it’s not provided, it will throw us the already known error:</p><pre>NullInjectorError: No provider for ApplePayPayments!</pre><h4><em>useClass:</em></h4><p>Another option is <em>useClass. </em>It tells Angular to create a <strong>new instance</strong> of the specified class. In our case, each time <em>ApplePayWidget</em> is created we would create a new instance of the <em>ApplePayPayments</em> class. In other words, lifetime of the instance of the <em>ApplePayPayments</em> service is bound to the component that provides that service.</p><pre>@Component({<br>  selector: &#39;app-apple-pay-widget&#39;,<br>  providers: [<br>    {<br>      provide: Payments,<br>      useClass: ApplePayPayments,<br>    },<br>  ],<br>})<br>export class ApplePayWidget extends PaymentWidget {</pre><h4>useValue:</h4><p>Provides a <strong>literal value</strong>, such as a string, number, object, or function. Useful for configuration values, constants, mock data.</p><pre>@Component({<br>  selector: &#39;app-apple-pay-widget&#39;,<br>  providers: [<br>    {<br>      provide: Payments,<br>      useValue: {<br>        pay(amount: number) {<br>          return amount;<br>        } <br>      },<br>    },<br>  ],<br>})<br>export class ApplePayWidget extends PaymentWidget {</pre><h4>useFactory:</h4><p>Uses a factory function to return the dependency. Great for conditional logic or derived services.</p><pre>@Component({<br>  selector: &#39;app-apple-pay-widget&#39;,<br>  providers: [<br>    {<br>      provide: Payments,<br>      useFactory: () =&gt; {<br>        const auth = inject(Auth);<br>        const role = auth.role(); // signal value of role of the user<br>        if (role === Role.DEV) {<br>          return FakeApplePayPayments;<br>        }<br>        else {<br>          return ApplePayPayments;<br>        }<br>      }<br>    },<br>  ],<br>})<br>export class ApplePayWidget extends PaymentWidget {</pre><h4>multi: true</h4><p>Allows multiple providers for the <strong>same token</strong>, and Angular will inject an <strong>array</strong> of all values. Often used with HttpInterceptors or similar.</p><h3>Conclusion:</h3><p>Dependency Injection is more than just a core concept in Angular — it’s the backbone of how scalable, testable, and maintainable applications are built. By abstracting away the creation and management of dependencies, Angular empowers developers to focus on business logic instead of wiring.</p><p>Next time you’re injecting a service, remember: you’re not just pulling in a class — you’re climbing the tree. :)</p><p>P.S. I’ll be writing more about Dependency Injection. Also, I am providing a <a href="https://stackblitz.com/edit/stackblitz-starters-rerzy4tg?file=src%2Fapp%2Fcore%2Fproviders%2Fapi-endpoint.provider.ts,src%2Fapp%2Fcore%2Fservices%2Fpayments.ts,src%2Fapp%2Fcore%2Fservices%2Fapi.ts,src%2Fapp%2Fcore%2Fservices%2Fapple-pay-payments.ts,src%2Fapp%2Fshared%2Fcomponents%2Fpaypal-widget%2Fpaypal-widget.ts,src%2Fapp%2Fshared%2Fcomponents%2Fapple-pay-widget%2Fapple-pay-widget.ts,src%2Fmain.ts">StackBlitz</a> that goes along with this article (and has some extras too).</p><h3>Bonus</h3><p>Have you heard of <a href="https://techstacknation.com/">TechStackNation</a>?</p><p><strong>Tech Stack Nation</strong> is a thriving <strong>free, private community for developers and software architects</strong> where participants collaborate, share knowledge, and build confidence in web application development — especially around Angular, TypeScript, enterprise architecture, and front-end tech.</p><p><a href="https://www.youtube.com/watch?v=nYHrbum6RWc&amp;t=2s">https://www.youtube.com/watch?v=nYHrbum6RWc</a></p><p>Feel free to join our cozy discussions. Wish you a good day :)</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24018eec12f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/dependency-injection-in-angular-climbing-up-the-tree-a24018eec12f">Dependency Injection in Angular: Climbing up the Tree</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Will Signals replace the Pipes in Angular?]]></title>
            <link>https://medium.com/@mrkrsticmilos/will-signals-replace-the-pipes-in-angular-750833859993?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/750833859993</guid>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 17:00:27 GMT</pubDate>
            <atom:updated>2025-06-19T17:00:27.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LtQr3Uhi3t9CKavwus2vg.png" /></figure><p>Ever since the <em>Signals</em> were introduced in Angular, I had a feeling that they will replace <em>Angular Pipes</em>. At least the <em>Pure Pipes</em>.</p><p>I think that the development of the new pipes will be definitely replaced with the computed signals. But what if we could replace the usage of the built in Pipes such as Currency Pipe with the Signals…</p><p>Using the <em>Dependency Injection</em> might be useful for this scenario. Since Pipes could be used as Injectables, we could create our derived computed for the provided value.</p><p>In order to use Pipe as Injectable, we would need to provide it on the application level. I want to try the experiment with the Currency Pipe.</p><p>Let’s create our <em>Environment Provider</em> that will replace the usage of the <em>Currency Pipe</em>.</p><p>We would need to create a new file for the provider. Let’s place it somewhere in the <em>app/providers/currency.provider.ts.</em> The very first step is to enable Currency Pipe as injectable. We would just need to provide its DI token.</p><pre>import { CurrencyPipe } from &quot;@angular/common&quot;;<br><br>export function provideCurrency(): EnvironmentProviders {<br>    return makeEnvironmentProviders([<br>        CurrencyPipe,<br>    ]);<br>}</pre><p><em>Encapsulated Environment Providers</em> that are only accepted during creation of an EnvironmentInjector (e.g. in an NgModule or AppConfig). Next step is to add the <em>provideCurrency</em> function in the providers array:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    ...<br>    provideCurrency()<br>  ]<br>};</pre><p>Now we are able to use the Currency Pipe as Injectable. Something like this:</p><pre>const currencyPipe = inject(CurrencyPipe);</pre><p>In other words, now we can inject the pipe as Dependency Injection and use it on the component level:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>})<br>export class App {<br>  private readonly currencyPipe = inject(CurrencyPipe);<br>}</pre><p>Now we can create a computed out of some signal value and display the formatted value.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    {{ totalAmount() }}<br>  `,<br>})<br>export class App {<br>  private readonly currencyPipe = inject(CurrencyPipe);<br>  protected readonly value = signal(100);<br>  protected readonly totalAmount = computed(() =&gt;<br>    this.currencyPipe.transform(this.value())<br>  );<br>}</pre><p>If we test in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xs8hk_tog976EFX9UyFXzg.png" /></figure><h4>Conclusion</h4><p>I like this approach because I can see in the component’s file what’s going on under the hood. Also, imports array will be shorter in the component’s decorator. Stacking multiple pipes would be done in similar fashion, just calling the transform function on the result of the previous value.</p><p>If we are using multiple pipes from the <em>Angular Common</em> module, we can actually rename <em>provideCurrency Environment Provider, </em>call it <em>provideCommonPipes</em> or something like that and import there all the necessary pipes and use them as Dependency Injection across the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750833859993" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple UI Store with Signals]]></title>
            <link>https://blog.stackademic.com/simple-ui-store-with-signals-ac6e83f9df25?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac6e83f9df25</guid>
            <category><![CDATA[ui-state]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-signals]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 04:46:57 GMT</pubDate>
            <atom:updated>2025-06-17T08:56:38.080Z</atom:updated>
            <content:encoded><![CDATA[<p>How to use Angular Signals to create reliable and predictable Web Apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFMkf0MC45Vr5xHs0vjkRQ.png" /></figure><h4>Intro</h4><p>In this article we are going to build a simple eCommerce Platform and we will use Signals, Signal based Inputs/Models, Linked Signal and the Effect, reactive function that tracks the signal dependencies.</p><p>Also, while we are waiting for the Signals based forms, in today’s article I am going to use Template Driven Forms which can click up with Signals in natural way.</p><h4>UI Store</h4><p>UI Store acts as a single point of truth for the part of the application. It manages the UI-centric state and it describes the application behavior. One Web Application can have multiple stores (local store or feature store).</p><h4>Signals</h4><p>Signals as the new reactive primitive are the natural new way how to handle reactivity of the Angular Web Applications. When compared to RxJS, Signals are very simple. Signals can hold one value over time.</p><p>Reading the signal value is simple — just call the getter function like this:</p><pre>const value = signal(0);<br>console.log(&#39;Read signal value by calling the getter: &#39;, value());<br>// Read signal value by calling the getter: 0</pre><p>And you can set or update the values like this:</p><pre>value.set(1);<br>console.log(&#39;Read signal value by calling the getter after set: &#39;, value());<br>// Read signal value by calling the getter after set: 1<br><br>value.update(v =&gt; v + 1);<br>console.log(&#39;Read signal value by calling the getter after update: &#39;, value());<br>// Read signal value by calling the getter after set: 2</pre><p>Unlike regular getter functions, Signals are memoized therefore calling the getter in the template won’t trigger the new change detection cycle until the value has actually changed.</p><pre>&lt;p&gt;Current value: {{ value() }}&lt;/p&gt;</pre><h4>Service Layer</h4><p>Our application has to provide the actual data from some API. In this case, we are going to <strong>mock</strong> the <em>fetching</em> of the Products from some <em>API</em>. Let’s build a Products Service like this:</p><pre>ng generate service services/products</pre><p>Once the file is generated, we can create our mocked API service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import { Product } from &#39;../interfaces/product.interface&#39;;<br><br>const PRODUCTS: Product[] = [<br>  {<br>    id: &#39;prod-001&#39;,<br>    name: &#39;Wireless Headphones&#39;,<br>    description:<br>      &#39;Noise-cancelling over-ear Bluetooth headphones with 30 hours battery life.&#39;,<br>    price: 129.99,<br>    inStock: true,<br>  },<br>  {<br>    id: &#39;prod-002&#39;,<br>    name: &#39;Smart Water Bottle&#39;,<br>    description:<br>      &#39;Tracks your water intake and glows to remind you to stay hydrated.&#39;,<br>    price: 49.99,<br>    inStock: true,<br>  },<br>  // ...<br>  {<br>    id: &#39;prod-009&#39;,<br>    name: &#39;Laptop Stand&#39;,<br>    description: &#39;Adjustable aluminum stand for laptops up to 17 inches.&#39;,<br>    price: 22.75,<br>    inStock: true,<br>  },<br>];<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ProductsService {<br>  getAll() {<br>    return of(PRODUCTS);<br>  }<br>}</pre><p>Also, we would need to define a Product interface. First, let’s generate the file by running the following command in the root of the project.</p><pre>ng generate interface interfaces/product</pre><p>And edit the Product interface file:</p><pre>export interface Product {<br>  id: string;<br>  name: string;<br>  description: string;<br>  price: number;<br>  inStock: boolean;<br>}</pre><h4>Products List Page</h4><p>For the purpose of this demo, I’ll make the application as simple as possible. I won’t implement the <em>Master/Details</em> page flow, I want to add the products to the <em>Shopping Cart</em> right here on the <em>Products List Page</em> (<em>App Component</em> in this example).</p><p>In order to load the products from the service, first we need to inject the service in our main component.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br>  `,<br>})<br>export class AppComponent {<br>  readonly productsService = inject(ProductsService);</pre><p>In the past, we would probably use ngOnInit method to subscribe to the Observable and then populate the data in the component like this:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br>  `,<br>})<br>export class App implements OnInit {<br>  readonly productsService = inject(ProductsService);<br>  private readonly destroyRef = inject(DestroyRef);<br>  <br>  products: Product[] = [];<br><br>  ngOnInit(): void {<br>    this.productsService.getAll()<br>      .pipe(takeUntilDestroyed(this.destroyRef))<br>      .subscribe(products =&gt; this.products = products);<br>  }</pre><p>We would need to unsubscribe as well as a general rule when working with RxJS Observable streams.</p><p>However, there is a nicer way. We could use the toSignal function to convert the Observable to Signals:</p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br>  `,<br>})<br>export class AppComponents {<br>  readonly productsService = inject(ProductsService);<br><br>  readonly products = toSignal(this.productsService.getAll(), {<br>    initialValue: [],<br>  });</pre><p>Cool thing about the <strong>toSignal</strong> function from the <em>@angular/core/rxjs-interop</em> package is that does the <strong>unsubscribe</strong> for us. Also, as you can see, much less boilerplate.</p><p>In order to display these products in the template, we would need to generate the Product Card component.</p><h4>Product Card Component</h4><p>The Product Card component will be a simple, presentational component with one input and one output.</p><p>But first, let’s generate:</p><pre>ng generate component components/product-card</pre><p>Let’s define our Product Card component:</p><pre>import { Component, input, computed, output } from &#39;@angular/core&#39;;<br>import { Product } from &#39;../../interfaces/product.interface&#39;;<br><br>@Component({<br>  selector: &#39;app-product-card&#39;,<br>  imports: [],<br>  templateUrl: &#39;./product-card.component.html&#39;,<br>  styleUrl: &#39;./product-card.component.css&#39;,<br>})<br>export class ProductCardComponent {<br>  readonly product = input.required&lt;Product&gt;();<br>  readonly addToCart = output&lt;Product&gt;();<br><br>  protected readonly stockAvailibility = computed(<br>    () =&gt; this.product().inStock ? &#39;In Stock&#39; : &#39;Out of Stock&#39;;<br>  );<br>}</pre><p>We have defined the signal based input for the product and one event emitter using the new output function.</p><p>Notice that we have introduced the <strong>Computed Signal</strong> which will be used to display the availability of the product based on the product input signal.</p><p>And the template will look like this:</p><pre>&lt;div class=&quot;product-card&quot;&gt;<br>  &lt;h2 class=&quot;product-name&quot;&gt;{{ product().name }}&lt;/h2&gt;<br>  &lt;p class=&quot;product-description&quot;&gt;{{ product().description }}&lt;/p&gt;<br>  &lt;p class=&quot;product-price&quot;&gt;${{ product().price }}&lt;/p&gt;<br>  &lt;p class=&quot;product-stock&quot; [class.out-of-stock]=&quot;!product().inStock&quot;&gt;<br>    {{ stockAvailibility() }}<br>  &lt;/p&gt;<br>  &lt;button<br>    class=&quot;add-button&quot;<br>    (click)=&quot;addToCart.emit(product())&quot;<br>    [disabled]=&quot;!product().inStock&quot;<br>  &gt;<br>    Add to Cart<br>  &lt;/button&gt;<br>&lt;/div&gt;</pre><p>Styling:</p><pre>.product-card {<br>  border: 1px solid #ccc;<br>  padding: 1rem;<br>  border-radius: 6px;<br>  margin-bottom: 1rem;<br>  max-width: 100%;<br>}<br><br>.product-name {<br>  font-size: 1.25rem;<br>  margin: 0 0 0.5rem;<br>}<br><br>.product-description {<br>  font-size: 0.95rem;<br>  color: #555;<br>}<br><br>.product-price {<br>  font-weight: bold;<br>  margin: 0.5rem 0;<br>}<br><br>.product-stock {<br>  font-size: 0.9rem;<br>  color: green;<br>}<br><br>.product-stock.out-of-stock {<br>  color: red;<br>}<br><br>.add-button {<br>  padding: 0.5rem 1rem;<br>  font-size: 0.9rem;<br>  border: none;<br>  border-radius: 4px;<br>  background-color: #007bff;<br>  color: white;<br>  cursor: pointer;<br>}<br><br>.add-button:disabled {<br>  background-color: #aaa;<br>  cursor: not-allowed;<br>}</pre><h4>Displaying of the Products</h4><p>Remember how we prepared the products signal that comes from the RxJS Observable using <em>toSignal</em> function? Now it’s time to display products cards in our AppComponent:</p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { ProductCardComponent } from &#39;./app/components/product-card/product-card.component&#39;;<br>import { ProductsService } from &#39;./app/services/products.service&#39;;<br>import { Product } from &#39;./app/interfaces/product.interface&#39;;<br>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [<br>    ProductCardComponent,<br>  ],<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br>    <br>    &lt;div&gt;<br>      @for (product of products(); track product.id) {<br>        &lt;app-product-card [product]=&quot;product&quot; (addToCart)=&quot;false&quot;/&gt;<br>      }<br>    &lt;/div&gt;<br>  `,<br>})<br>export class AppComponents {<br>  readonly productsService = inject(ProductsService);<br><br>  readonly products = toSignal(this.productsService.getAll(), {<br>    initialValue: [],<br>  });<br>}</pre><p>Notice that we are not handling the <em>addToCart</em> event at this point. For that we would need to start implementing our UI Store.</p><p>Before we do that, let’s check out the products list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUcFOc3TfX2zjTLScG0h-w.png" /></figure><h4>Shopping Cart Store</h4><p>In the past, if you didn’t want to use <em>NgRx</em>, <em>Akita</em> or similar UI Store solutions in your Angular projects, you would probably use RxJS and BehaviorSubject. Similar vibes here: instead of RxJS we are going to use Signals.</p><p>Let’s create Shopping Cart Store as an Angular Service:</p><pre>ng generate service stores/shopping-cart-store</pre><p>The idea is that store’s sole responsibility is to hold the data. No side effects, just pure data storing and couple of methods that comes along with it.</p><p>Let’s define our <em>models/interfaces</em> in the same file as the service:</p><pre>export interface CustomerDetails {<br>  firstName: string;<br>  lastName: string;<br>  street: string;<br>  city: string;<br>  postalCode: string;<br>}<br><br>export interface ShoppingCartItem {<br>  product: Product;<br>  quantity: number;<br>}<br><br>export interface ShoppingCartStore {<br>  items: ShoppingCartItem[];<br>  totalPrice: number;<br>  customerDetails: CustomerDetails;<br>  discount: number;<br>}</pre><p>Feel free to move each interface to the appropriate file but for the purpose of the easier reading and learning, I’ll keep it here.</p><p>Our centralized feature store for the <strong>Shopping Cart</strong> will hold the information what <em>items</em> have been added to cart &amp; <em>quantity</em>, <em>customer information</em> such as name and place, optional <em>discount</em> and <em>total price</em> of the order.</p><p>Since store data is <strong>synchronous</strong>, we would need our start values.</p><pre>export interface CustomerDetails {<br>  ...<br>}<br><br>export interface ShoppingCartItem {<br>  ...<br>}<br><br>export interface ShoppingCartStore {<br>  ...<br>}<br><br>const INITIAL_ITEMS: ShoppingCartItem[] = [];<br><br>const INITAL_CUSTOMER_DETAILS: CustomerDetails = {<br>  firstName: &#39;&#39;,<br>  lastName: &#39;&#39;,<br>  street: &#39;&#39;,<br>  city: &#39;&#39;,<br>  postalCode: &#39;&#39;,<br>};<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  </pre><p>We can start implementing our store like this:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  readonly #customerDetails = signal&lt;CustomerDetails&gt;(INITAL_CUSTOMER_DETAILS);<br>  readonly #discount = signal(0);<br>  readonly #totalPrice = computed(() =&gt; {<br>    return this.#items().reduce(<br>      (sum, item) =&gt; sum + item.product.price * item.quantity,<br>      0<br>    );<br>  });</pre><p><em>Shopping Cart Store Items</em>, <em>Customer Details</em> and <em>Discount</em> are regular <strong>Writable Signals</strong>. Notice that we used private # accessor to make our Store data protected from writing from the outside world.</p><p><em>Shopping Cart Store Total Price</em> is a <strong>Computed</strong> which tracks the dependency of the value of the <em>Shopping Cart Store Items</em> and takes <em>quantity</em> into consideration when calculating <strong>total price</strong> of the order.</p><p>We can expose each store element as readonly from outside world in two ways:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStore {<br>  ...<br>  readonly #customerDetails = signal&lt;CustomerDetails&gt;(INITAL_CUSTOMER_DETAILS);<br>  ...<br><br>  // 1st approach:<br>  readonly customerDetails = this.#customerDetails.asReadonly();<br>  <br>  // 2nd approach:<br>  readonly customerDetails = computed(() =&gt; ({...this.#customerDetails()}));</pre><p>I prefer computed given that we can still access the value of the object reference so we can create a new instance with spread operator. The reason why I am preferring that approach is because we don’t want to mutate the reference itself. More on that later.</p><p>Since we have our very first <em>‘selector like’</em> piece of the store, let’s show it in the <em>UI</em> somehow. Since we are expecting the input from the user, let’s create a form, template driven form this time.</p><pre>ng generate component components/customer-details-form</pre><p>Our component would need to import <em>FormsModule</em> from the <em>@angular/forms</em> package and we will define one input and one output.</p><pre>@Component({<br>  selector: &#39;app-customer-details-form&#39;,<br>  imports: [FormsModule],<br>  templateUrl: &#39;./customer-details-form.component.html&#39;,<br>  styleUrl: &#39;./customer-details-form.component.css&#39;,<br>})<br>export class CustomerDetailsFormComponent {<br>  readonly customer = input.required&lt;CustomerDetails&gt;();<br>  readonly submit = output&lt;CustomerDetails&gt;();<br>}</pre><p>And its template:</p><pre>&lt;form #customerForm=&quot;ngForm&quot;&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;firstName&quot;&gt;First Name:&lt;/label&gt;<br>    &lt;input<br>      id=&quot;firstName&quot;<br>      name=&quot;firstName&quot;<br>      [(ngModel)]=&quot;customer().firstName&quot;<br>      required<br>      #firstName=&quot;ngModel&quot;<br>    /&gt;<br>    @if (!firstName.valid &amp;&amp; !firstName.pristine) {<br>    &lt;div&gt;First name is required.&lt;/div&gt;<br>    }<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;lastName&quot;&gt;Last Name:&lt;/label&gt;<br>    &lt;input<br>      id=&quot;lastName&quot;<br>      name=&quot;lastName&quot;<br>      [(ngModel)]=&quot;customer().lastName&quot;<br>      required<br>      #lastName=&quot;ngModel&quot;<br>    /&gt;<br>    @if (!lastName.valid &amp;&amp; !lastName.pristine) {<br>    &lt;div&gt;Last name is required.&lt;/div&gt;<br>    }<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;street&quot;&gt;Street:&lt;/label&gt;<br>    &lt;input<br>      id=&quot;street&quot;<br>      name=&quot;street&quot;<br>      [(ngModel)]=&quot;customer().street&quot;<br>      required<br>      #street=&quot;ngModel&quot;<br>    /&gt;<br>    @if (!street.valid &amp;&amp; !street.pristine) {<br>    &lt;div&gt;Street is required.&lt;/div&gt;<br>    }<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;city&quot;&gt;City:&lt;/label&gt;<br>    &lt;input<br>      id=&quot;city&quot;<br>      name=&quot;city&quot;<br>      [(ngModel)]=&quot;customer().city&quot;<br>      required<br>      #city=&quot;ngModel&quot;<br>    /&gt;<br>    @if (!city.valid &amp;&amp; !city.pristine) {<br>    &lt;div&gt;City is required.&lt;/div&gt;<br>    }<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;postalCode&quot;&gt;Postal Code:&lt;/label&gt;<br>    &lt;input<br>      id=&quot;postalCode&quot;<br>      name=&quot;postalCode&quot;<br>      [(ngModel)]=&quot;customer().postalCode&quot;<br>      required<br>      pattern=&quot;^[0-9]{5}$&quot;<br>      #postalCode=&quot;ngModel&quot;<br>    /&gt;<br>    @if (!postalCode.valid &amp;&amp; !postalCode.pristine) {<br>    &lt;div&gt;Postal code is required.&lt;/div&gt;<br>    }<br>  &lt;/div&gt;<br><br>  &lt;button type=&quot;button&quot; (click)=&quot;submit.emit(customer())&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Notice that each property of the input signal customer is bidden via <em>NgModel</em> directive and that we are emitting the customer details on button click. That’s why we destructed the object itself in the store. Otherwise we would mutate data directly in memory and might have some unwanted side effects.</p><p>Now let’s go back to the <em>App Component</em> where we are stacking all these presentational component and injecting the services/stores.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [<br>    ProductCardComponent,<br>    CustomerDetailsFormComponent,<br>  ],<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br><br>    &lt;div&gt;<br>      &lt;app-customer-details-form [customer]=&quot;customerDetails()&quot; (submit)=&quot;addCustomer($event)&quot;/&gt;<br>    &lt;/div&gt;<br><br>    &lt;div&gt;<br>      @for (product of products(); track product.id) {<br>        &lt;app-product-card [product]=&quot;product&quot; (addToCart)=&quot;false&quot;/&gt;<br>      }<br>    &lt;/div&gt;<br>  `,<br>})<br>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br><br>  readonly products = toSignal(this.productsService.getAll(), {<br>    initialValue: [],<br>  });<br>  readonly customerDetails = this.shoppingCartService.customerDetails;<br><br>  addCustomer(customerDetails: CustomerDetails) {<br>    console.log(&#39;customerDetails&#39;, customerDetails);<br>  }</pre><p>Let’s see the progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7QYMXuL7Wk4SzLeuOyZpw.png" /></figure><h4>UI Store methods</h4><p>Let’s define a couple of methods in our store.</p><p>The very first method we can implement is adding to cart functionality. Let’s edit the <em>Shopping Cart Store Service</em> file:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  ...<br><br>  addItem(product: Product, quantity: number = 1) {<br>    this.#items.update((items: ShoppingCartItem[]) =&gt; {<br>      const index = items.findIndex((item) =&gt; item.product.id === product.id);<br><br>      if (index &gt; -1) {<br>        const updatedItems = [...items];<br>        const existingItem = updated[index];<br>        updatedItems[index] = {<br>          ...existingItem,<br>          quantity: existingItem.quantity + quantity,<br>        };<br>        return updatedItems;<br>      }<br><br>      return [...items, { product, quantity }];<br>    });<br>  }</pre><p>First we check if the product with the same <em>ID</em> exists. If it does, we would update the quantity, otherwise add the new item.</p><p>Next thing we are going to do is go back to the <em>App Component</em> where we can handle the item addition to the cart on user click on the button in the <em>Product Card Component</em>.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [<br>    ProductCardComponent,<br>    CustomerDetailsFormComponent,<br>  ],<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br><br>    &lt;div&gt;<br>      &lt;app-customer-details-form [customer]=&quot;customerDetails()&quot; (submit)=&quot;addCustomer($event)&quot;/&gt;<br>    &lt;/div&gt;<br><br>    &lt;div&gt;<br>      @for (product of products(); track product.id) {<br>        &lt;app-product-card [product]=&quot;product&quot; (addToCart)=&quot;addToCart($event)&quot;/&gt;<br>      }<br>    &lt;/div&gt;<br>  `,<br>})<br>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br><br>  readonly products = toSignal(this.productsService.getAll(), {<br>    initialValue: [],<br>  });<br>  readonly customerDetails = this.shoppingCartService.customerDetails;<br><br>  addCustomer(customerDetails: CustomerDetails) {<br>    console.log(&#39;customerDetails&#39;, customerDetails);<br>  }<br><br>  addToCart(product: Product) {<br>    this.shoppingCartService.addItem(product);<br>  }</pre><p>Now we need to display these data on the UI to make sure our Store works. Let’s create a component Shopping Cart Details where we can display our Store content.</p><pre>@Component({<br>  selector: &#39;app-shopping-cart-details&#39;,<br>  imports: [CurrencyPipe],<br>  templateUrl: &#39;./shopping-cart-details.component.html&#39;,<br>  styleUrl: &#39;./shopping-cart-details.component.css&#39;,<br>})<br>export class ShoppingCartDetailsComponent {<br>  readonly shoppingCart = input.required&lt;ShoppingCartStore&gt;();<br><br>  protected readonly fullName = computed(() =&gt; {<br>    const firstName = this.shoppingCart().customerDetails.firstName;<br>    const lastName = this.shoppingCart().customerDetails.lastName;<br><br>    if (!firstName &amp;&amp; !lastName) {<br>      return null;<br>    } else {<br>      return `${firstName} ${lastName}`;<br>    }<br>  });<br><br>  protected readonly address = computed(() =&gt; {<br>    const street = this.shoppingCart().customerDetails.street;<br>    const postalCode = this.shoppingCart().customerDetails.postalCode;<br>    const city = this.shoppingCart().customerDetails.city;<br><br>    if (!street &amp;&amp; !postalCode &amp;&amp; !city) {<br>      return null;<br>    } else {<br>      return `${street}, ${postalCode} ${city}`;<br>    }<br>  });<br>}</pre><p>The purely presentational component itself will have one input — the whole Shopping Cart Store object. Let’s define the template:</p><pre>&lt;div class=&quot;shopping-cart-details&quot;&gt;<br>  &lt;p&gt;<br>    Full name: &lt;strong&gt;{{ fullName() }}&lt;/strong&gt;<br>  &lt;/p&gt;<br>  &lt;p&gt;<br>    Address: &lt;strong&gt;{{ address() }}&lt;/strong&gt;<br>  &lt;/p&gt;<br>  &lt;div&gt;<br>    &lt;ul&gt;<br>      @for (item of shoppingCart().items; track item.product.id) {<br>      &lt;li&gt;<br>        &lt;strong&gt;{{ item.product.name }}&lt;/strong&gt; ({{ item.quantity }} x<br>        {{ item.product.price | currency }})<br>        &lt;span<br>          &gt;&lt;button (click)=&quot;false&quot;&gt;<br>            -<br>          &lt;/button&gt;&lt;/span<br>        &gt;<br>      &lt;/li&gt;<br>      } @empty {<br>      &lt;li&gt;No products in the shopping cart&lt;/li&gt;<br>      }<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>  &lt;p&gt;<br>    Total price: &lt;strong&gt;{{ shoppingCart().totalPrice | currency }}&lt;/strong&gt;<br>  &lt;/p&gt;<br>&lt;/div&gt;</pre><p>Now we know what we want to display to the user, we need to make this data accessible from the store. Once again, we are going to use computed signal.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  readonly #customerDetails = signal&lt;CustomerDetails&gt;(INITAL_CUSTOMER_DETAILS);<br>  readonly #discount = signal(0);<br>  readonly #totalPrice = computed(() =&gt; {<br>    return this.#items().reduce(<br>      (sum, item) =&gt; sum + item.product.price * item.quantity,<br>      0<br>    );<br>  });<br><br>  ...<br><br>  readonly shoppingCart = computed&lt;ShoppingCartStore&gt;(() =&gt; {<br>    return {<br>      items: [...this.#items()],<br>      totalPrice: this.#totalPrice(),<br>      customerDetails: { ...this.#customerDetails() },<br>      discount: this.#discount(),<br>    };<br>  });</pre><p>Now we can <em>reference</em> this signal value in the <em>App Component</em>:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [<br>    ProductCardComponent,<br>    ShoppingCartDetailsComponent,<br>    CustomerDetailsFormComponent,<br>  ],<br>  template: `<br>    &lt;h1&gt;eCommerce Demo&lt;/h1&gt;<br><br>    &lt;div&gt;<br>      &lt;app-shopping-cart-details [shoppingCart]=&quot;shoppingCart()&quot; (applyDiscount)=&quot;applyDiscount()&quot; (removeProduct)=&quot;removeProduct($event)&quot;&gt;<br>    &lt;/div&gt;<br><br>    &lt;div&gt;<br>      &lt;app-customer-details-form [customer]=&quot;customerDetails()&quot; (submit)=&quot;addCustomer($event)&quot;/&gt;<br>    &lt;/div&gt;<br><br>    &lt;div&gt;<br>      @for (product of products(); track product.id) {<br>        &lt;app-product-card [product]=&quot;product&quot; (addToCart)=&quot;addToCart($event)&quot;/&gt;<br>      }<br>    &lt;/div&gt;<br>  `,<br>})<br>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br>  ...<br><br>  protected readonly shoppingCart = this.shoppingCartService.shoppingCart;<br><br>  ...<br>  addCustomer(customerDetails: CustomerDetails) {<br>    console.log(&#39;customerDetails&#39;, customerDetails);<br>  }<br><br>  addToCart(product: Product) {<br>    this.shoppingCartService.addItem(product);<br>  }</pre><p>Since we are at it, let’ connect the dots for the customer details as well. Adding a customer to the store would be done in similar fashion. In our Store Service, we can add another method:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  readonly #customerDetails = signal&lt;CustomerDetails&gt;(INITAL_CUSTOMER_DETAILS);<br>  ...<br><br>  addCustomer(customerDetails: CustomerDetails) {<br>    this.#customerDetails.set({ ...customerDetails });<br>  }</pre><p>And let’s hook it up in the App Component:</p><pre>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br>  ...<br><br>  addCustomer(customerDetails: CustomerDetails) {<br>    this.shoppingCartService.addCustomer(customerDetails);<br>  }</pre><p>Let’s test the UI: Submit the form and add a couple of products to the store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uou-oQvrmRLOYdeY0T7iOg.png" /></figure><p>I admit, UI is not that great but it display the data. :)</p><p>While we are at it, let’s add the remove product handler. Let’s go back to the <em>Shopping Cart Store Service</em> and add a new method:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  ...  <br>  readonly #totalPrice = linkedSignal(() =&gt; {<br>    return this.#items().reduce(<br>      (sum, item) =&gt; sum + item.product.price * item.quantity,<br>      0<br>    );<br>  });<br><br>  decreaseProductQuantity(productId: string, amount: number = 1): void {<br>    this.#items.update((items: ShoppingCartItem[]) =&gt;<br>      items.flatMap((item) =&gt;<br>        item.product.id === productId<br>          ? item.quantity &gt; amount<br>            ? [{ ...item, quantity: item.quantity - amount }]<br>            : []<br>          : [item]<br>      )<br>    );<br>  }</pre><p>We will use <em>flat map</em> to either decrease the quantity or remove the product completely from the items array. We will use the update method on the Writable Signal <em>#items</em>.</p><pre>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br>  ...<br><br>  removeItem(productId: string) {<br>    this.shoppingCartStoreService.decreaseProductQuantity(productId);<br>  }</pre><h4>LinkedSignal</h4><p>What if we want to implement some weird discount logic that will be possible for user to grab but only if certain conditions are met.</p><p>For the start, let’s add a <strong>Apply Discount button</strong> in the <em>Shopping Cart Details</em> component. Let’s start with the component file. We want to enable the button only if total price is greater than $150,00 and customer can only use the discount once.</p><pre>@Component({<br>  selector: &#39;app-shopping-cart-details&#39;,<br>  imports: [CurrencyPipe],<br>  templateUrl: &#39;./shopping-cart-details.component.html&#39;,<br>  styleUrl: &#39;./shopping-cart-details.component.css&#39;,<br>})<br>export class ShoppingCartDetailsComponent {<br>  readonly shoppingCart = input.required&lt;ShoppingCartStore&gt;();<br>  readonly applyDiscount = output&lt;void&gt;();<br>  readonly removeItem = output&lt;string&gt;();<br>  readonly discountApplied = signal&lt;boolean&gt;(false);<br><br><br>  onApplyDiscount() {<br>    this.discountApplied.set(true);<br>    this.applyDiscount.emit();<br>  }</pre><p>And edit its template file:</p><pre>&lt;div class=&quot;shopping-cart-details&quot;&gt;<br>  ...<br><br>  &lt;button<br>    (click)=&quot;onApplyDiscount()&quot;<br>    [disabled]=&quot;discountApplied() || shoppingCart().totalPrice &lt; 150&quot;<br>  &gt;<br>    Apply discount<br>  &lt;/button&gt;<br><br>  @if (discountApplied()) {<br>  &lt;p&gt;<br>    Applied discount: &lt;strong&gt;{{ shoppingCart().discount }}%&lt;/strong&gt;<br>  &lt;/p&gt;<br>  }</pre><p>On <em>Apply discount button click</em> we are emitting the event and also disabling user from emitting the same event again.</p><p>In the <em>App Component</em> file we can handle the emitted event.</p><pre>export class AppComponent {<br>  readonly productsService = inject(ProductsService);<br>  readonly shoppingCartStoreService = inject(ShoppingCartStoreService);<br>  ...<br><br>  applyDiscount() {<br>    this.shoppingCartStoreService.applyDiscount();<br>  }</pre><p>And now we need to do implement the method in the <em>Shopping Cart Store Service</em>. But how we can do that? If the total price is already computed, we could generate a discount percentage and recalculate the total amount. However, that approach would apply the same discount for each added item to the cart.</p><p>In order not to use some hacky effects or flag variables, <em>linkedSignal</em> comes to the rescue. :)</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  readonly #items = signal&lt;ShoppingCartItem[]&gt;(INITIAL_ITEMS);<br>  readonly #customerDetails = signal&lt;CustomerDetails&gt;(INITAL_CUSTOMER_DETAILS);<br>  readonly #discount = signal(0);<br>  readonly #totalPrice = linkedSignal(() =&gt; {<br>    return this.#items().reduce(<br>      (sum, item) =&gt; sum + item.product.price * item.quantity,<br>      0<br>    );<br>  });<br>  ...<br><br>  applyDiscount() {<br>    if (this.#discount() === 0) {<br>      const discount = Math.floor(Math.random() * 21);<br>      this.#discount.set(discount);<br>      this.#totalPrice.update((value) =&gt; (value * (100 - discount)) / 100);<br>    }<br>  }</pre><p>As you can see, <em>Linked Signal</em> acts as a both <strong>Computed</strong> and <strong>Writable Signal</strong>.</p><p>When we defined its value, we used computation. However, in the <em>applyDiscount</em> method are updating the total price with newly generated discount amount using the update method.</p><p>Each additional addition of the item to the store would trigger the computation again and discount would not be considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hp-VjhFohI0DVlzd83N3OQ.png" /></figure><h4>Effects</h4><p><em>Effects</em> has to be used <strong>with</strong> <strong>caution</strong>.</p><p>Effects should be used for</p><ul><li>syncing the signal values which are not possible to be done via computed or linkedSignal.</li><li>updating CSS variables in the host element</li><li>syncing with local storage</li><li>to emit the output function value</li></ul><blockquote>Do not use effects for async updates on non-reactive variables<br>- <a href="https://courses.techstacknation.com/"><strong><em>Connie Leung</em></strong></a>, Google Developer Expert for Angular</blockquote><p>For the purpose of this article, we are going to synchronize the value of the customer with the <em>localStorage</em>. <em>Keep It Simple, Stupid</em>.</p><p>Effects has to be defined on the <strong>constructor</strong> level so we would do something like this in our <em>Shopping Cart Store Service</em>:</p><pre>const CUSTOMER_DETAILS_STORAGE_KEY = &#39;customerDetails&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class ShoppingCartStoreService {<br>  ...<br>  <br>  constructor() {<br>    const customerDetails = JSON.parse(<br>      localStorage.getItem(CUSTOMER_DETAILS_STORAGE_KEY) || &#39;null&#39;<br>    );<br>    if (customerDetails) {<br>      this.#customerDetails.set(customerDetails);<br>    }<br><br>    effect(() =&gt; {<br>      const customerDetails = this.#customerDetails();<br>      localStorage.setItem(<br>        CUSTOMER_DETAILS_STORAGE_KEY,<br>        JSON.stringify(customerDetails)<br>      );<br>    });<br>  }</pre><p>Notice that we are checking if there is already the value in the store for the customer. If there are, we would update the <em>customerDetails</em> signal.</p><p>After that, we are defining an effect that will set customer data into the <em>localStorage</em>.</p><p>One thing to keep in mind, <em>effects</em> are triggered at least once.</p><h4>Conclusion</h4><p>Custom Angular Signal Stores offer a lightweight, fine-grained alternative to traditional state management solutions. By leveraging Angular’s reactivity model through signals, developers can build highly performant, modular, and intuitive stores without the overhead of external libraries. Whether you’re replacing complex NgRx setups or simply managing UI state in a more controlled way, custom signal stores provide a powerful pattern that aligns with Angular’s evolving ecosystem. As the framework continues to embrace signals-first architecture, mastering this approach will position your applications — and your skills — for long-term success.</p><h4>Bonus</h4><p>If you are interested in leveling up your knowledge about Angular Signals, I highly recommend <a href="https://courses.techstacknation.com/">Connie Leung’s course</a>.</p><p>Also, here’s the link to the <a href="https://stackblitz.com/edit/stackblitz-starters-m1xsumf3?file=src%2Fapp%2Fcomponents%2Fproducts-filter-form%2Fproducts-filter-form.component.ts">StackBlitz</a> with whole implementation of the custom UI Store with Signals.</p><p>I hope you liked reading this article.</p><p>Wish you a good day!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac6e83f9df25" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/simple-ui-store-with-signals-ac6e83f9df25">Simple UI Store with Signals</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signals vs RxJS // Short story]]></title>
            <link>https://medium.com/@mrkrsticmilos/signals-vs-rxjs-short-story-ba23cd3476a7?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba23cd3476a7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[signal]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 18:39:11 GMT</pubDate>
            <atom:updated>2024-08-01T18:39:11.381Z</atom:updated>
            <content:encoded><![CDATA[<p>Async? Go RxJS. Sync? Go Signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luEb0s7_ZAfiFQ0_OuzkBA.png" /><figcaption><a href="https://x.com/BenLesh/status/1775207971410039230">https://x.com/BenLesh/status/1775207971410039230</a></figcaption></figure><p>That’s it. Have a good day.</p><p><a href="https://www.youtube.com/shorts/gx6ZpYUm-B8">https://www.youtube.com/shorts/gx6ZpYUm-B8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba23cd3476a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signals & Reactive Forms? Why not!]]></title>
            <link>https://blog.stackademic.com/angular-signals-reactive-forms-8b096e21459d?source=rss-7aa9d7a6dbf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b096e21459d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Miloš Krstić]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 13:21:53 GMT</pubDate>
            <atom:updated>2024-11-25T17:21:09.794Z</atom:updated>
            <content:encoded><![CDATA[<p>The Angular Renaissance II</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*b-JQHZ82qL4UNW1DvpErsg.png" /><figcaption>End result on the actual project’s production. :)</figcaption></figure><h4>Intro</h4><p>Most of the <em>enterprise</em> projects have some kind of <strong>form handling</strong> and form handling is hard. There are a couple of ways that Angular framework provides to handle the forms. You could use <em>Forms Module</em>, <em>Reactive Forms Module</em> or even the new signal based <em>Models</em>.</p><p>Until recently, for any complex form handling Reactive Forms were the way to go. Personally, I am a big fan of the <em>Reactive Forms</em>. I consider it one of the best features of Angular framework from its inception.</p><p>Things could change with new Models based on signals implementation but if you are familiar with <em>Reactive Forms</em> you could use them with <em>Signals</em> and <em>RxJS/interop package</em> quite naturally.</p><p><strong>RxJS/interop</strong> package contains interop helper functions and types for use with RxJS. You might have used <strong>takeUntilDestroyed</strong> pipeable operator which comes from this package.</p><p>Here I will be focusing on Signals, Reactive Forms and how to combine them using the above mentioned package. Also, I am mentioning the HostAttributeToken as well. In order to follow along, you would need to understand the <em>Reactive Forms</em> but also to have basic understanding of <em>Signals</em>.</p><h4>The Old Way &amp; The New Way</h4><p><em>Reactive Forms</em> are based on <strong>RxJS</strong>. Let’s assume you and your teammates are familiar with Reactive Forms and you want to migrate towards more modern approach. Say no more, I feel you, <em>RxJS/interop</em> comes to the rescue!</p><p>Here’s the scenario. You are building a form that contains multiple select options component with additional checkbox to select all values and search field to filter out the options. Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*RjKawq9HpEOx_fBRU7OisA.png" /><figcaption>Form UI</figcaption></figure><p>We have a form that contains the <em>label</em>, <em>search</em> input, <em>single checkbox </em>and the <em>list of options (checkboxes) </em>that could be selected. Each input is a part of the <em>Form Group</em> where <em>search</em> and <em>select all</em> controls are simple <em>Form Controls</em> and the list of options is contained within the <em>Form Array</em>. So let’s create our form like this in the newly created component <em>Multiple Select Form</em>:</p><pre>@Component({<br>  selector: &#39;mk-multiple-select-form&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule],<br>  templateUrl: &#39;./multiple-select-form.component.html&#39;,<br>  styleUrl: &#39;./multiple-select-form.component.scss&#39;<br>})<br>export class MultipleSelectFormComponent {<br>  readonly form = new FormGroup({<br>    search: new FormControl&lt;string&gt;(&#39;&#39;),<br>    selectAll: new FormControl&lt;boolean&gt;(false),<br>    options: new FormArray&lt;any&gt;([])<br>  });<br>  readonly optionsControl = this.form.get(&#39;options&#39;) as FormArray;</pre><p>As usual, since we are working with Reactive Forms we are importing the module so we could bind the above form to the template. Notice that we added the <em>optionsControl</em> property. It does not change anything except the surface area of the component will be more readable. And let’s bind the form to our template.</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>    &lt;p&gt;&lt;strong&gt;{{ label }}&lt;/strong&gt;&lt;/p&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;search&quot; formControlName=&quot;search&quot; placeholder=&quot;Filter options&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;checkbox&quot; formControlName=&quot;selectAll&quot;&gt; Select All<br>    &lt;/div&gt;<br>    &lt;ng-container formArrayName=&quot;options&quot;&gt;<br>        &lt;ul&gt;<br>            @for (group of optionsControl.controls; track group) {<br>              &lt;li [formGroupName]=&quot;$index&quot;&gt;<br>                  ...<br>              &lt;/li&gt;<br>            }<br>        &lt;/ul&gt;<br>    &lt;/ng-container&gt;<br>&lt;/form&gt;</pre><p>The usual form binding except that we are using the new control flow to iterate through the form array’s controls and look how nice it looks!</p><p>But our form is pretty dumb at this point. Let’s make it more customizable. Notice that we lack <em>label </em>property in our component. We could use input (the old one or the signal based one) for that but since I don’t expect those values to be changed, I am going to use <em>HostAttributeToken</em> which is a new way to use <em>@Attribute</em> parameter decorator.</p><p><strong>Host Attribute Tokens</strong><em> (@Attribute) </em>are similar to the inputs except that they are <em>static</em>. Value provided initially will not be changed during the lifecycle of the component and therefore will not check for further change detections. The name you provide in the HostAttributeToken constructor will be the name of the attribute of the <em>component or directive</em>.</p><pre>@Component({<br>  ...<br>})<br>export class MultipleSelectFormComponent {<br>  readonly label = inject(new HostAttributeToken(&#39;label&#39;));<br><br>  readonly form = new FormGroup({...});</pre><p>And you bind the label value in the parent component like this:</p><pre>&lt;mk-multiple-select-form label=&quot;Choose your destiny&quot;/&gt;</pre><p>Now we need to add an input for our select options. The type of the option will be <em>any</em> because I want this form to work with different types of data. Also, I would introduce two new <em>Host Attribute Tokens</em> which are <em>optional</em>. That way we can determine what will be a value and display label for each option. If we do not provide those Host Attribute Tokens, values will be <em>null</em>.</p><pre>export class MultipleSelectFormComponent {<br>  readonly label = inject(new HostAttributeToken(&#39;label&#39;));<br><br>  // option label key &amp; option value key<br>  readonly optionLabelKey = inject(<br>    new HostAttributeToken(&#39;optionLabelKey&#39;), { optional: true}<br>  );<br>  readonly optionValueKey = inject(<br>    new HostAttributeToken(&#39;optionValueKey&#39;), { optional: true}<br>  );<br>  <br>  // options input<br>  readonly options = input.required&lt;any[]&gt;();<br><br>  readonly form = new FormGroup({...});<br>  readonly optionsControl = this.form.get(&#39;options&#39;) as FormArray;</pre><p>As you can see, we made our <em>options input required</em> so if we will get <em>compilation error</em> if we do not provide options to select.</p><p>In the past, we would need to use lifecycle hooks or setter functions to populate our <em>options form array. </em>I am going to use computed in this case since I want my form array to be populated in sync with options input value change. Also, I am going to clear the options form array on each change.</p><pre>export class MultipleSelectFormComponent {<br>  ...<br>  <br>  // options input<br>  readonly options = input.required&lt;any[]&gt;();<br><br>  // form declaration<br>  readonly form = new FormGroup({...});<br>  readonly optionsControl = this.form.get(&#39;options&#39;) as FormArray;<br><br>  // computed form array<br>  readonly optionsFormArray = computed&lt;FormArray&gt;(() =&gt; {<br>    this.optionsControl.clear();<br>    this.populateOptionsFormArray(this.options(), this.optionLabelKey, this.optionValueKey);<br><br>    return this.optionsControl;<br>  });<br><br>  // helper function to populate form array from options<br>  private populateOptionsFormArray(options: any[], labelKey: string | null, valueKey: string | null) {<br>    options.forEach(option =&gt; {<br>      this.optionsControl.push(new FormGroup({<br>        checked: new FormControl(false),<br>        value: new FormControl(valueKey ? option[valueKey] : option),<br>        label: new FormControl(labelKey ? `${option[labelKey]}` : `${option}`)<br>      }), { <br>        emitEvent: false<br>      });<br>    });<br>  }</pre><p>Notice that we track the <em>options input signal</em> value change by calling its getter method as an input argument for the helper function <em>populateOptionsFormArray </em>in the <em>computed optionsFormArray signal</em>.</p><p>The helper function would push new Form Group to our options form array. Notice that we are not emitting an event when adding a new form group. The structure of the Form Group will be like this:</p><pre>export interface OptionFormGroup {<br>  checked: boolean;<br>  value: any;<br>  label: string;<br>}</pre><p>That is important because we are going to bind our options form array in the template like this:</p><pre>&lt;ng-container formArrayName=&quot;filters&quot;&gt;<br>  &lt;ul&gt;<br>    @for (group of optionsFormArray().controls; track group.value) {<br>      &lt;li [formGroupName]=&quot;$index&quot;&gt;<br>        &lt;input type=&quot;checkbox&quot; formControlName=&quot;checked&quot;&gt;<br>        &lt;label&gt;{{ group.value.label }}&lt;/label&gt;<br>      &lt;/li&gt;<br>    }<br>  &lt;/ul&gt;<br>&lt;/ng-container&gt;</pre><p>We are binding the form group name which is the index of the element in the form array on the list item. We are binding the checked form control name to the checkbox and displaying the label. Also, notice that we changed the track function in the new for loop to track the elements value as well that we replaced the <em>optionsControl form array </em>with the <em>optionsFormArray() computed signal</em>.</p><h4>Filter The Options</h4><p>Next thing I want to do is to filter the options presented on UI based on the search input value change.</p><p>As we already mentioned, Reactive Forms are based on RxJS and Observables but we want to handle the value the Signal way. How can we do that? We can use the new <em>toSignal </em>helper function from <em>@angular/core/rxjs-interop</em> package which converts the Observable to Signal. Cool thing about that is that you don’t have to worry about memory leaks and unsubscribing. How cool is that?</p><pre>export class MultipleSelectFormComponent {<br>  ...<br><br>  readonly form = new FormGroup({<br>    search: new FormControl&lt;string&gt;(&#39;&#39;),<br>    selectAll: new FormControl&lt;boolean&gt;(false),<br>    options: new FormArray&lt;any&gt;([])<br>  });<br><br>  // search signal created from Observable using toSignal function<br>  readonly search = toSignal(this.form.get(&#39;search&#39;)!.valueChanges, {<br>    initialValue: this.form.get(&#39;search&#39;)!.value<br>  });</pre><p>The first argument of the <em>toSignal</em> function is the observable source. The second one is optional but since Signals require initial value, we are going to set the one we set in the form building.</p><p>Now we need to filter the form array displayed on UI. We can filter directly in the template with custom made <em>Is Substring Pipe </em>which we can use with new<em> if control flow</em>.</p><pre>ng generate pipe pipes/is-substring</pre><p>Let’s define out transform function in newly created pipe:</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;isSubstring&#39;,<br>  standalone: true<br>})<br>export class IsSubstringPipe implements PipeTransform {<br><br>  transform(value: string, query: string | null): boolean {<br>    if (!query || !value) {<br>      return true;<br>    }<br>    else {<br>      return value.toLocaleLowerCase().includes(query.toLocaleLowerCase());<br>    }<br>  }<br>}</pre><p>Before we filter out in the template, we need to import <em>Is Substring Pipe</em> in the <em>Multiple Select Form Component </em>like this:</p><pre>@Component({<br>  selector: &#39;mk-multiple-select-form&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, IsSubstringPipe], // &lt;-----<br>  templateUrl: &#39;./multiple-select-form.component.html&#39;,<br>  styleUrl: &#39;./multiple-select-form.component.scss&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class MultipleSelectFormComponent {</pre><p>Let’s go back to the <em>Multiple Select Form Component’s Template</em>:</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>    &lt;p&gt;&lt;strong&gt;{{ label }}&lt;/strong&gt;&lt;/p&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;search&quot; formControlName=&quot;search&quot; placeholder=&quot;Filter options&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;checkbox&quot; formControlName=&quot;selectAll&quot;&gt; Select All<br>    &lt;/div&gt;<br>    &lt;ng-container formArrayName=&quot;options&quot;&gt;<br>        &lt;ul&gt;<br>            @for (group of optionsFormArray().controls; track group.value) {<br>              @if(group.value.label | isSubstring:search()) {<br>                &lt;li [formGroupName]=&quot;$index&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; formControlName=&quot;checked&quot; /&gt;<br>                  &lt;label&gt;{{ group.value.label }}&lt;/label&gt;<br>                &lt;/li&gt;<br>              } <br>            }<br>        &lt;/ul&gt;<br>    &lt;/ng-container&gt;<br>&lt;/form&gt;</pre><p>Let’s give it a try:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*RPt1ApTCSTNFW6cpxn5cFA.gif" /><figcaption>Filtering the options</figcaption></figure><h4>Handle Select All Checkbox</h4><p>Let’s make our <em>Select All</em> checkbox toggle the change of options selection. If checked — select all, if deselected — deselect all. :)</p><pre>export class MultipleSelectFormComponent {<br>  ...<br>  <br>  readonly selectAll = toSignal(this.form.get(&#39;selectAll&#39;)!.valueChanges, { <br>    initialValue: null<br>  });</pre><p>Once again I am using the <em>toSignal</em> function to create a signal from the <em>Select All</em> control’s value change Observable but in this case I am going to use the initial value as <em>null</em>. I’ll explain later why to <em>null</em> and not to <em>false</em>. :)</p><p>Every time Select All control/signal value changes I want to update the value for each form group in the form array.</p><p>But how we could achieve that? If we use the above mentioned computed signals, I’m afraid we are going to cause more problems. For example, if we expand the filtering computed signal to track the <em>selectAll</em> signals along with <em>search </em>signal, we might select or deselect values on search input change and we don’t want to do that and those two inputs are independent on each other.</p><p>In this case I am going to use <em>effect </em>since it is a side effect of the Select All checkbox state toggle<em>. </em>One thing to keep in mind, <em>effects</em> must be used with <strong>caution</strong>. According to the <a href="https://angular.dev/guide/signals#use-cases-for-effects">official documentation</a>:</p><blockquote>Effects are rarely needed in most application code, but may be useful in specific circumstances.</blockquote><p>Let’s define our effect like this:</p><pre>export class MultipleSelectFormComponent {<br>  ...<br>  constructor() {<br>    effect(() =&gt; {<br>      this.optionsControl.controls<br>        .forEach(<br>          (group) =&gt; group.get(&#39;checked&#39;)!.setValue(this.selectAll()));<br>    });<br>  }</pre><p>Pretty simple. Iterate through form array, set the value from the <em>selectAll</em> signal and that’s it. But there is <strong>an issue</strong> with this approach. Initially, when we are populating form array from the options input, we are setting the value for each form array element to false. And than we are iterating through the same form array to set the value from the selectAll signal.</p><p>Since effects run at least once, that’s where the initial value of <strong>null</strong> comes handy. Every time user clicks on Select All checkbox, the value would be either <em>true</em> or <em>false</em>. Let’s refactor a bit:</p><pre>constructor() {<br>  effect(() =&gt; {<br>    const selectAll = this.selectAll();<br>    if (selectAll !== null) {<br>      this.handleSelectAll(selectAll);<br>    }<br>  });<br>}<br>  <br>...<br><br>private handleSelectAll(selectAll: boolean | null): void {<br>  this.filters.controls<br>      .forEach((group) =&gt; group.get(&#39;checked&#39;)!.setValue(selectAll));<br>}</pre><h4>Stuck In A Box</h4><p>So far so good. We can select and deselect options, filter them, etc, but our parent is not aware of any changes. We could subscribe to the form’s value changes or use the toSignal helper function again with the effect and use the new output function or the old output event emitter to emit..</p><p>But there is a better way!</p><p>Thanks to the <em>@angular/core/rxjs-interop </em>package, you can create an output from observable with the function called <em>outputFromObservable</em>. Basically, it looks like this:</p><pre>readonly valueChange = outputFromObservable&lt;any&gt;(<br>    this.form.valueChanges<br>);</pre><p>Rather than emitting the entire form object we want to emit only the selected options value. Let’s refactor and use some RxJS magic here.</p><pre>export class MultipleSelectFormComponent {<br>  ...<br>  readonly valueChange = outputFromObservable&lt;any[]&gt;(<br>    this.optionsControl.valueChanges.pipe(<br>      map(this.filterSelectedOptions),<br>    )<br>  );<br><br>  ...<br><br>  private filterSelectedOptions(formGroups: OptionFormGroup[]): any[] {<br>    return formGroups<br>      .filter((group: OptionFormGroup) =&gt; group.checked)<br>      .map(group =&gt; group.value);<br>  }</pre><p>Now we map the filters form array value changes by filtering the selected options (checked) and map to return the value of the form group.</p><p>In our parent component we can bind attributes, input and output like this:</p><pre>&lt;mk-multiple-select-form<br>          label=&quot;Choose your destiny&quot;<br>          optionLabelKey=&quot;skill&quot;<br>          optionValueKey=&quot;id&quot;<br>          [options]=&quot;multipleSelectOptions&quot;<br>          (valueChange)=&quot;optionsSelectionChange($event)&quot; /&gt;</pre><p>In our parent we need to define our options and the handler function called when options selection change.</p><pre>export class AppComponent {<br>  <br>  readonly multipleSelectOptions = [<br>    { id: 1, skill: &#39;Frontend Developer&#39;}, <br>    { id: 2, skill: &#39;Backend Developer&#39;}, <br>    { id: 3, skill: &#39;Fullstack Developer&#39;}<br>  ];<br><br>  optionsSelectionChange(options: any[]) {<br>    console.log(&#39;optionsSelectionChange&#39;, options);<br>  }</pre><p>Let’s give it a try:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nRGiKvAobWfwfog2VvA-TA.gif" /></figure><p>Everything works as expected except for one small detail. If I click select all, output will emit a new value for each option selected and I clicked on <em>Select All</em> only once. That is happening because of the nature of RxJS and this problem has a name: <em>The Diamond Problem</em>, the problem signals themselves are solving.</p><p>The Diamond Problems occurs in RxJS when your observable source is combining multiple streams and you are updating those streams <em>synchronously </em>(and we are doing that when iterating through form array to set the value from selectAll signal)<em>. </em>Even though we are using Signals here, the producer of the value is still the Observable source.</p><p>There is kind of a dirty solution to this. Adding a <em>debounceTime</em> operator in the pipeline will make the output ‘wait’ before mapping and emitting the new changes.</p><pre>readonly valueChange = outputFromObservable&lt;any[]&gt;(<br>  this.filters.valueChanges.pipe(<br>    debounceTime(0),<br>    map(this.filterSelectedOptions),<br>  )<br>);</pre><h4>Conclusion</h4><p><em>The Angular Team</em> wants to make <strong>RxJS</strong> <strong>optional</strong> in the future. RxJS is hard because async programming is hard. On the other hand, they will expand the support for <em>RxJS</em> with <em>RxJS/interop package</em> for nerds like me who love working with Observables. One thing to keep in mind, <em>RxJS/interop package</em> is still in a <strong>developer preview</strong>.</p><p>Working with <em>Signals</em>, <em>New Control Flow</em> and everything mentioned above is a joy to me. The future of Angular looks very promising.</p><p>I hope this article wasn’t too long and that you gained something out of it. The idea was to combine the old way and the new way because they work together very nicely (except for the dirty solution to The Diamond Problem). It’s going to take some time before Signals become a standard but so far so good.</p><p>Last but not the least, once again I remind you to use <em>effects</em> with <strong>caution</strong> because they are <strong>asynchronous</strong>. I call them <em>the necessary evil</em>. :)</p><p>Everything you have read so far would click up very nicely with <em>Dynamic Forms in Angular</em>. If you are not familiar with the Dynamic Forms pattern in Angular, I recommend you to check out <a href="https://www.youtube.com/live/jMOkkvB3vGM">Pavel Suk on NG Asia meetup</a>.</p><p>Thank you for your attention. Wish you a great day!</p><p>P.S. I’ll post the whole code for the component so you could easily see the whole picture yourself. Let’s add the final touch: <br><strong><em>changeDetection: ChangeDetectionStrategy.OnPush.</em></strong></p><pre>import { ChangeDetectionStrategy, Component, computed, effect, HostAttributeToken, inject, input } from &#39;@angular/core&#39;;<br>import { FormArray, FormControl, FormGroup, ReactiveFormsModule } from &#39;@angular/forms&#39;;<br>import { debounceTime, map } from &#39;rxjs&#39;;<br>import { outputFromObservable, toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br>import { IsSubstringPipe } from &#39;../../pipes/string-is-substring.pipe&#39;;<br><br>export interface OptionFormGroup {<br>  checked: boolean;<br>  value: any;<br>  label: string;<br>}<br><br>@Component({<br>  selector: &#39;mk-multiple-select-form&#39;,<br>  standalone: true,<br>  imports: [ReactiveFormsModule, IsSubstringPipe],<br>  templateUrl: &#39;./multiple-select-form.component.html&#39;,<br>  styleUrl: &#39;./multiple-select-form.component.scss&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class MultipleSelectFormComponent {<br>  readonly label = inject(new HostAttributeToken(&#39;label&#39;));<br>  readonly optionLabelKey = inject(new HostAttributeToken(&#39;optionLabelKey&#39;), { optional: true});<br>  readonly optionValueKey = inject(new HostAttributeToken(&#39;optionValueKey&#39;), { optional: true});<br>  readonly options = input.required&lt;any[]&gt;();<br><br>  readonly form = new FormGroup({<br>    search: new FormControl&lt;string&gt;(&#39;&#39;),<br>    selectAll: new FormControl&lt;boolean&gt;(false),<br>    options: new FormArray&lt;any&gt;([])<br>  });<br>  private readonly optionsControl = this.form.get(&#39;options&#39;) as FormArray;<br><br>  private readonly selectAll = toSignal(this.form.get(&#39;selectAll&#39;)!.valueChanges, { <br>    initialValue: null<br>  });<br>  private readonly search = toSignal(this.form.get(&#39;search&#39;)!.valueChanges, {<br>    initialValue: this.form.get(&#39;search&#39;)!.value<br>  });<br><br>  private readonly optionsFormArray = computed&lt;FormArray&gt;(() =&gt; {<br>    this.optionsControl.clear();<br>    this.populateOptionsFormArray(this.options(), this.optionLabelKey, this.optionValueKey);<br><br>    return this.optionsControl;<br>  });<br><br>  readonly filteredOptionsFormGroups = computed&lt;FormGroup[]&gt;(() =&gt; {<br>    const search = this.search() || &#39;&#39;;<br>    return this.optionsFormArray()<br>      .controls<br>      .filter(group =&gt; group.value.label.toLocaleLowerCase().includes(search.toLocaleLowerCase())) as FormGroup[]; <br>  });<br><br>  readonly valueChange = outputFromObservable&lt;any[]&gt;(<br>    this.optionsControl.valueChanges.pipe(<br>      debounceTime(0),<br>      map(this.filterSelectedOptions),<br>    )<br>  );<br><br>  constructor() {<br>    effect(() =&gt; {<br>      const selectAll = this.selectAll();<br>      if (selectAll !== null) {<br>        this.handleSelectAll(selectAll);<br>      }<br>    });<br>  }<br><br>  private populateOptionsFormArray(options: any[], labelKey: string | null, valueKey: string | null): void {<br>    options.forEach(option =&gt; {<br>      this.optionsControl.push(new FormGroup({<br>        checked: new FormControl(false),<br>        value: new FormControl(valueKey ? option[valueKey] : option),<br>        label: new FormControl(labelKey ? `${option[labelKey]}` : `${option}`)<br>      }), { <br>        emitEvent: false<br>      });<br>    });<br>  }<br><br>  private handleSelectAll(selectAll: boolean | null): void {<br>    this.optionsControl<br>      .controls<br>      .forEach((group) =&gt; group.get(&#39;checked&#39;)!.setValue(selectAll));<br>  }<br><br>  private filterSelectedOptions(formGroups: OptionFormGroup[]): any[] {<br>    return formGroups<br>      .filter((group: OptionFormGroup) =&gt; group.checked)<br>      .map(group =&gt; group.value);<br>  }<br>}</pre><p>And the template:</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>    &lt;p&gt;&lt;strong&gt;{{ label }}&lt;/strong&gt;&lt;/p&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;search&quot; formControlName=&quot;search&quot; placeholder=&quot;Filter options&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        &lt;input type=&quot;checkbox&quot; formControlName=&quot;selectAll&quot;&gt; Select All<br>    &lt;/div&gt;<br>    &lt;ng-container formArrayName=&quot;options&quot;&gt;<br>        &lt;ul&gt;<br>            @for (group of optionsFormArray().controls; track group.value) {<br>              @if(group.value.label | isSubstring:search()) {<br>                &lt;li [formGroupName]=&quot;$index&quot;&gt;<br>                  &lt;input type=&quot;checkbox&quot; formControlName=&quot;checked&quot; /&gt;<br>                  &lt;label&gt;{{ group.value.label }}&lt;/label&gt;<br>                &lt;/li&gt;<br>              } <br>            }<br>        &lt;/ul&gt;<br>    &lt;/ng-container&gt;<br>&lt;/form&gt;</pre><p>I hope this wasn’t too long. If you encounter any problems, feel free to reach out on <a href="https://www.linkedin.com/in/mustackio/">LinkedIn</a>.</p><p>Wish you a great day!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b096e21459d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/angular-signals-reactive-forms-8b096e21459d">Signals &amp; Reactive Forms? Why not!</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>