<?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 Rafael Kapp on Medium]]></title>
        <description><![CDATA[Stories by Rafael Kapp on Medium]]></description>
        <link>https://medium.com/@e.kapprafael?source=rss-43dad64495d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MpceG9PmnmvJ-ka97PFttg.jpeg</url>
            <title>Stories by Rafael Kapp on Medium</title>
            <link>https://medium.com/@e.kapprafael?source=rss-43dad64495d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:37:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@e.kapprafael/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[The dialog that ate my sticky header]]></title>
            <link>https://medium.com/@e.kapprafael/the-dialog-that-ate-my-sticky-header-af111030d0ad?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/af111030d0ad</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 16:01:02 GMT</pubDate>
            <atom:updated>2026-07-08T16:01:02.658Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How moving the scroll container fixed a bug I didn’t see coming.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8uq08PELrwp7FsvMZqTRw.png" /><figcaption>Sticky header gets eaten by a modal dialog monster.</figcaption></figure><h3>The symptom</h3><p>We had a page with a sticky header — the kind that stays pinned to the top while you scroll. Simple, boring, works everywhere. Until you opened a modal dialog.</p><p>The moment the dialog appeared, the sticky header behind it would <em>jump or disappear</em>. It only happened with dialogs open, which made it feel random and hard to pin down.</p><h3>The setup that caused it</h3><p>Here’s the thing that mattered, and it’s easy to miss: <em>what element was actually scrolling.</em></p><p>By default, a web page scrolls on the document root — the `&lt;html&gt;`/`&lt;body&gt;`. That’s the outermost scroll container, and everything (the sticky header, the page content, a “scroll to top” button) was written against it. Scroll events came from the window. Sticky positioning was relative to the document.</p><p>That’s a totally normal setup. It just doesn’t play nicely with modal dialogs.</p><h3>Why the dialog broke it</h3><p>When a modal dialog opens, it wants to stop the page <strong>behind</strong> it from scrolling — you’ve seen this: the backdrop appears and the background freezes. The way most UI libraries do this is a <em>scroll-blocking strategy</em>: they temporarily lock the scroll on whatever the scroll container is.</p><p>And our scroll container was the document root. So to lock it, the library did what these strategies do — it pinned the root element (roughly `position: fixed`), stashed the current scroll offset, and restored it on close.</p><p>That temporary re-pinning of the root is exactly what a sticky header hates. Sticky positioning is calculated relative to its scroll container. Yank that container out from under it — even for a moment, even to “freeze” it — and the header loses its reference point. It jumps, it disappears, and the scroll offset gets shuffled around on the way in and out.</p><p>So nothing was really “broken.” The dialog was doing its job. It just happened to fight over the exact same element our header depended on.</p><h3>The fix: give the page its own scroll container</h3><p>Instead of letting the whole document scroll, we made the scroll happen <em>one level in</em> — on the app’s main layout element.</p><p>The change is small but the shift in thinking is the whole point:</p><pre>/* Before: the document root scrolls */<br>html, body {<br> overflow: auto;<br> height: 100%;<br>}<br>/* After: the document root never scrolls… */<br>html, body {<br> height: 100%;<br> overflow: hidden;<br>}<br>/* …the layout element does */<br>.app-layout {<br> height: 100vh;<br> overflow-y: auto;<br>}</pre><p>Now there are two separate players:</p><ul><li>The <em>document root</em> is frozen and never scrolls.</li><li>The <em>layout element</em> is where all the real scrolling — and the sticky header — lives.</li></ul><p>When a dialog opens and reaches for the document root to lock it… there’s nothing to lock. The root wasn’t scrolling anyway. The dialog does its thing in peace, and the layout element — along with its sticky header — is never touched. The header stays exactly where it should.</p><h3>The ripple: everything listening to “the window”</h3><p>There was a catch. A bunch of code assumed the window was the thing that scrolls:</p><ul><li>the sticky header’s shadow-on-scroll effect,</li><li>a “back to top” button that appeared after scrolling down,</li><li>the `window.scrollTo(…)` call that button used.</li></ul><p>Once the window stopped scrolling, all of those went quiet — they were listening to an element that no longer moves. So the second half of the fix was re-pointing every scroll listener from the window to the new scroll container: listen to <strong>its</strong> scroll events, read <strong>its</strong> scroll offset, and call <strong>its</strong> `scrollTo`.</p><p>This is the part that’s easy to forget. Changing <strong>what scrolls</strong> means every piece of code that reacts to scrolling has to be told where to look now.</p><h3>What I’d tell past me</h3><p>Two lessons worth remembering:</p><ol><li><strong>”What scrolls?” is a real design decision, not an accident.</strong> The document root is the default, but it’s shared territory — dialogs, overlays, and libraries all assume they can grab it. Giving your app its own scroll container keeps that shared thing out of your critical UI.</li><li><strong>Sticky elements are only as stable as their scroll container.</strong> If something can re-position or freeze that container out from under them, they’ll misbehave. A dialog’s scroll lock is exactly that kind of “something.”</li></ol><p>The fix ended up being a few lines of CSS and moving some listeners around. The hard part was seeing that a modal dialog and a sticky header were quietly fighting over the same element — and that the answer wasn’t to fix either one, but to stop making them share.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af111030d0ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Attribute Selectors Beat Element Selectors for Directives]]></title>
            <link>https://medium.com/@e.kapprafael/why-attribute-selectors-beat-element-selectors-for-directives-d61175f21634?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61175f21634</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 11:07:50 GMT</pubDate>
            <atom:updated>2026-06-02T11:07:50.553Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently rewrote a big chunk of our design system’s directives, swapping element selectors for attribute selectors. It touched a lot of files and fixed a problem we’d shipped on purpose.</p><p>Here’s the reasoning, written up loosely as an architecture decision record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcSJ_M5K1WxPXhcPO-lcoA.png" /><figcaption>Generated With Love By Myself</figcaption></figure><h3>The context</h3><p>These were always directives — but with an element selector, so they behaved like drop-in components:</p><pre>@Directive({<br>  selector: &#39;card-title&#39;,<br>})<br>export class CardTitleDirective {}</pre><pre>&lt;card-title&gt;Quarterly report&lt;/card-title&gt;</pre><p>The intent was convenience. Consumers shouldn’t have to think about <em>which</em> element to use — they’d just drop in &lt;card-title&gt; and get the right look. No decisions, no foot-guns.</p><p>The trouble is what lands in the DOM:</p><pre>&lt;card-title&gt;Quarterly report&lt;/card-title&gt;</pre><p>That’s not a heading. It’s a custom element styled to look like one. A screen reader finds no heading there. Keyboard users navigating by heading skip past it. The document outline has holes. And the “don’t worry about it” convenience is exactly what caused this — by removing the decision, we also removed the consumer’s ability to ship a real &lt;h2&gt;.</p><h3>The decision</h3><p>Use attribute selectors, and let the host element carry the semantics.</p><pre>@Directive({<br>  selector: &#39;[cardTitle]&#39;,<br>})<br>export class CardTitleDirective {}</pre><pre>&lt;h2 cardTitle&gt;Quarterly report&lt;/h2&gt;</pre><p>Now the DOM has a real &lt;h2&gt;. The directive still owns styling and behavior; the element owns meaning.</p><h3>Why it’s the better call</h3><p>The “convenience” we were proud of was really us deciding our consumers’ HTML for them — and that decision is almost always wrong, because the right heading level depends on where the component sits. A card on a landing page and the same card in a modal need different levels. Only the consumer knows.</p><p>With a real &lt;h2&gt;, accessibility is free: no role=&quot;heading&quot;, no aria-level, nothing to drift out of sync. The browser and the screen reader just work. The same goes beyond headings — a directive on a real &lt;button&gt; inherits the focus, keyboard, and form behavior you&#39;d otherwise reimplement badly.</p><h3>The trade-offs</h3><p>&lt;h2 cardTitle&gt; asks a bit more of the consumer, and they can now pick the wrong element. We took that deal: a small risk of misuse with an escape hatch beats a guaranteed-wrong default with none. Docs and a lint rule cover most of the gap.</p><p>Renaming selectors is also a breaking change, so it needs a deprecation window and a clear upgrade path. We did it in one pass rather than letting both styles linger.</p><h3>The takeaway</h3><p>Making a directive feel like a no-decisions component is tempting, but “no decisions” really means <em>we</em> made the decision — and we made it wrong. Attribute selectors hand semantics back to the element where they belong, and accessibility comes along for free.</p><p>If you’re reaching for an element selector, ask: does this <em>have</em> to be its own element, or am I just taking a decision that isn’t mine to make?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61175f21634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking Child Components in Angular Unit Tests]]></title>
            <link>https://medium.com/@e.kapprafael/mocking-child-components-in-angular-unit-tests-548fb0ccbdeb?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/548fb0ccbdeb</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[angular-atelier]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 15:56:51 GMT</pubDate>
            <atom:updated>2025-10-10T15:56:51.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKi9sjFQXpFObvsGOda7gw.png" /></figure><p>Unit tests in Angular should test only the component under test. Avoid pulling in other parts of the application, as that leads to irrelevant failures and unclear test results.</p><p>A common error that occurs when this isolation is broken is:<br> NG0201: No provider found for _SomeDependency.</p><p>The Angular injector cannot resolve a dependency required by a child component or one of its services.</p><p>There are two ways to address this:</p><ol><li><strong>Provide all dependencies</strong><br> Manually provide every dependency used by child components or injected services. This approach effectively turns the unit test into a partial integration test.</li><li><strong>Mock child components and dependencies</strong><br> Mocking isolates the unit completely and prevents unrelated dependencies from leaking into the test. This is the preferred approach for clean unit testing.</li></ol><p><em>Example with ng-mocks:</em></p><pre>import { provideZonelessChangeDetection } from &#39;@angular/core&#39;;<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { App } from &#39;./app&#39;;<br>import { MockComponent } from &#39;ng-mocks&#39;;<br>import { ChildComponent } from &#39;./child-component/child-component&#39;;<br><br>describe(&#39;App&#39;, () =&gt; {<br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      imports: [App, MockComponent(ChildComponent)],<br>    }).compileComponents();<br>  });<br><br>  it(&#39;should create the app&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(App);<br>    const app = fixture.componentInstance;<br>    expect(app).toBeTruthy();<br>  });<br>});</pre><p><em>Example without external libraries:</em></p><pre>import {Component, input, output, provideZonelessChangeDetection} from &#39;@angular/core&#39;;<br>import {TestBed} from &#39;@angular/core/testing&#39;;<br>import {App} from &#39;./app&#39;;<br>import {ChildComponent} from &#39;./child-component/child-component&#39;;<br><br><br>@Component({<br>  selector: &#39;app-child-component&#39;,<br>  template: &#39;&#39;,<br>})<br>export class MockChildComponent {<br>  public readonly someInput = input&lt;string&gt;();<br>  public readonly someOutput = output&lt;void&gt;();<br>}<br><br>describe(&#39;App&#39;, () =&gt; {<br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      imports: [App],<br>    }).overrideComponent(App,<br>      {<br>        add: {imports: [MockChildComponent]},<br>        remove: {imports: [ChildComponent]}<br>      })<br>      .compileComponents();<br>  });<br><br>  it(&#39;should create the app&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(App);<br>    const app = fixture.componentInstance;<br>    expect(app).toBeTruthy();<br>  });<br>});</pre><h4>Conclusion</h4><p>This approach replaces the real child with a mock, ensuring the parent’s test remains fully isolated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548fb0ccbdeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Nested Reactive State with Signals]]></title>
            <link>https://medium.com/@e.kapprafael/handling-nested-reactive-state-with-signals-9ca5f2258568?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ca5f2258568</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[ngrx-signalstore]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 19:38:25 GMT</pubDate>
            <atom:updated>2025-09-11T19:38:25.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TeHFbVrbJUzgXDcyAeHYA.png" /><figcaption>Created with the help of AI by the Autor</figcaption></figure><p>With Angulars signals, local state management feels easier than ever.</p><p>But when you deal with <strong>lists of heterogeneous items</strong> signals alone quickly run into limitations. Let’s see why, and how <strong>NgRx SignalStore with </strong><strong>withEntities</strong> makes this a breeze.</p><h3>The Dashboard UI</h3><p>Imagine a simple dashboard where users can add <strong>charts, tables, and stats</strong>. Each type renders differently, and each has its own interactions.</p><p>To keep this article focused, we won’t cover add/remove operations or boilerplate. Instead, we’ll look at <strong>three typical methods that mutate nested state</strong>:</p><ul><li>renaming a chart</li><li>adding a row to a table</li><li>incrementing a stat</li></ul><p>Here’s the template:</p><pre>&lt;div class=&quot;dashboard&quot;&gt;<br>  @for (widget of widgets(); track widget.id) {<br>    &lt;div class=&quot;widget&quot;&gt;<br>      @switch (widget.type) {<br>        @case (&#39;chart&#39;) {<br>          &lt;h3&gt;{{ widget.title }}&lt;/h3&gt;<br>          &lt;button (click)=&quot;renameChart(widget)&quot;&gt;Rename&lt;/button&gt;<br>        }<br>        @case (&#39;table&#39;) {<br>          &lt;ul&gt;<br>            @for (row of widget.rows; track $index) {<br>              &lt;li&gt;{{ row }}&lt;/li&gt;<br>            }<br>          &lt;/ul&gt;<br>          &lt;button (click)=&quot;addRow(widget)&quot;&gt;+ Row&lt;/button&gt;<br>        }<br>        @case (&#39;stat&#39;) {<br>          &lt;h2&gt;{{ widget.value }}&lt;/h2&gt;<br>          &lt;button (click)=&quot;incrementStat(widget)&quot;&gt;+1&lt;/button&gt;<br>        }<br>      }<br>    &lt;/div&gt;<br>  }<br>&lt;/div&gt;</pre><h3>Attempt 1: Plain Signals (Fails for Nested Updates)</h3><p>We start with a plain signal holding an array of widgets:</p><pre>export type DashboardWidget =<br>  | { id: string; type: &#39;chart&#39;; title: string }<br>  | { id: string; type: &#39;table&#39;; rows: string[] }<br>  | { id: string; type: &#39;stat&#39;; value: number };</pre><pre>widgets = signal&lt;DashboardWidget[]&gt;([]);</pre><p>Now, the three update methods:</p><pre>renameChart(widget: DashboardWidget) {<br>  if (widget.type === &#39;chart&#39;) {<br>    widget.title = &#39;Updated Chart&#39;; // ❌ no reactivity<br>  }<br>}<br><br>addRow(widget: DashboardWidget) {<br>  if (widget.type === &#39;table&#39;) {<br>    widget.rows.push(`Row ${widget.rows.length + 1}`); // ❌ no reactivity<br>  }<br>}<br><br>incrementStat(widget: DashboardWidget) {<br>  if (widget.type === &#39;stat&#39;) {<br>    widget.value++; // ❌ no reactivity<br>  }<br>}</pre><h3>Why it doesn’t work</h3><ul><li>Angular signals are <strong>shallow</strong>. They only react when the <strong>array reference</strong> changes.</li><li>Mutating nested objects (value++, push, direct assignment) doesn’t notify Angular.</li><li>Fixing this requires manual cloning of arrays/objects, which quickly gets verbose and error-prone.</li></ul><h3>Attempt 2: SignalStore with withEntities (The Right Way)</h3><p>With NgRx SignalStore, we normalize widgets as entities. This gives us <strong>built-in CRUD methods</strong> and fine-grained reactivity.</p><h3>Store</h3><pre>import { signalStore, withEntities } from &#39;@ngrx/signals&#39;;<br><br>export const DashboardStore = signalStore(<br>  { providedIn: &#39;root&#39; },<br>  withEntities&lt;DashboardWidget&gt;(),<br>);</pre><h3>Component</h3><pre>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  templateUrl: &#39;./dashboard.component.html&#39;, // template from above<br>})<br>export class DashboardComponent {<br>  store = inject(DashboardStore);<br>  <br>  renameChart(id: string) {<br>    this.store.updateEntity({<br>      id,<br>      changes: { title: &#39;Updated Chart&#39; },<br>    });<br>  }<br><br>  addRow(widget: DashboardWidget) {<br>    if (widget.type === &#39;table&#39;) {<br>      this.store.updateEntity({<br>        id,<br>        changes: { rows: [...widget.rows, `Row ${widget.rows.length + 1}`] },<br>      });<br>    }<br>  }<br><br>  incrementStat(widget: DashboardWidget) {<br>    if (widget.type === &#39;stat&#39;) {<br>      this.store.updateEntity({<br>        id,<br>        changes: { value: widget.value + 1 },<br>      });<br>    }<br>  }<br>}</pre><h3>Why This Works Better</h3><ul><li><strong>Automatic reactivity</strong>: updateEntity replaces just the changed object, triggering updates.</li><li><strong>Cleaner code</strong>: No manual cloning required.</li><li><strong>Scalable</strong>: Works smoothly for large lists of heterogeneous items.</li></ul><h3>Conclusion</h3><p>Plain signals are great for simple cases, but <strong>nested reactive state</strong> (like a list of widgets with different properties) is a pain point. Updates don’t propagate unless you manually clone arrays and objects.</p><p>With <strong>NgRx SignalStore and </strong><strong>withEntities</strong>:</p><ul><li>State is normalized.</li><li>Updates are fine-grained and declarative.</li></ul><p>The result? A dashboard that’s reactive, scalable, and maintainable — without nested signal headaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ca5f2258568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Unit Testing in v20.x: Choosing the Right Test Runner]]></title>
            <link>https://javascript.plainenglish.io/angular-unit-testing-in-v20-x-choosing-the-right-test-runner-cafe3f80115e?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cafe3f80115e</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jasmine]]></category>
            <category><![CDATA[vitest]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 19:52:07 GMT</pubDate>
            <atom:updated>2025-09-05T00:25:37.671Z</atom:updated>
            <content:encoded><![CDATA[<p>Front-end development moves fast — and Angular keeps pace. With v20 and v20.2.0 we’ve seen substantial feature and tooling upgrades (including Signals enhancements, zoneless capabilities, and build pipeline improvements). Testing is evolving alongside them: Karma is now deprecated, and the CLI offers experimental support for Vitest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYey-AIl5i-GXMxJ-bPk7w.png" /></figure><h3>Test Runner vs. Test Framework: Clarifying the Roles</h3><p>Let’s start with clearing things out. It’s vital to separate the roles of a <strong>test framework</strong> and a <strong>test runner</strong>, although they are often conflated:</p><ul><li>A <strong>test framework</strong> (or library) defines how you write tests — the structure of test suites, test cases, and assertions. Examples include Jasmine, Jest, Chai.</li><li>A <strong>test runner</strong> is what executes those tests: it finds them, compiles/transpiles code, runs them in an environment (browser, Node.js), and reports results. Karma has historically served as this runner in Angular projects.</li></ul><p>Modern tools like <strong>Vitest</strong> or <strong>Jest</strong> blend both roles, providing both test APIs (like describe, it, expect) and the execution engine.</p><h3>Angular’s Current Landscape: Deprecating Karma and Embracing Vitest</h3><p>By default, Angular CLI has relied on Jasmine + Karma (ng test). However, <strong>Karma is officially deprecated</strong>. This change stems from Angular’s shift to a new build system (@angular/build) that no longer includes the Karma plugin — marking the start of a transition away from this long-standing infrastructure.</p><p>In response, Angular has enabled <strong>experimental support for Vitest</strong> via a new unit-test builder. You can switch by updating your angular.json like this:</p><pre>&quot;test&quot;: {<br>  &quot;builder&quot;: &quot;@angular/build:unit-test&quot;,<br>  &quot;options&quot;: {<br>    &quot;tsConfig&quot;: &quot;tsconfig.spec.json&quot;,<br>    &quot;buildTarget&quot;: &quot;::development&quot;,<br>    &quot;runner&quot;: &quot;vitest&quot;<br>  }<br>}</pre><p>This unlocks Vitest integration, including Watch Mode, Node.js execution with jsdom.</p><h3>Benefits of Vitest</h3><ul><li><strong>Ultra-fast startup and watch experience</strong>, leveraging Vite’s infrastructure — only affected tests rerun when you change code.</li><li><strong>Native ESM support</strong> and zero-config for TypeScript projects.</li><li><strong>Jest-compatible APIs</strong> and assertion syntax (expect) with familiar mocking capabilities (vi.fn()), smoothing the migration path.</li></ul><h3>My Take: Why I Stick With Jest (for Now)</h3><p>Even though Angular is clearly pushing toward Vitest as the long-term solution, I personally <strong>still prefer Jest</strong> at this stage. The main reasons:</p><ul><li><strong>Maturity &amp; stability</strong>: Jest has been around for years, with a huge ecosystem and reliable tooling.</li><li><strong>Familiarity</strong>: Many teams (including mine) already know Jest inside out — its APIs, mocking utilities, and ecosystem are second nature.</li><li><strong>Predictability</strong>: While Vitest support is still marked as experimental in Angular, Jest provides a battle-tested base without worrying about shifting ground.</li></ul><p>That doesn’t mean Vitest isn’t the future. Quite the opposite: Angular’s technical direction makes it clear that Vitest is set to become the preferred option. But until the Angular team publishes a final, official recommendation — and Vitest integration leaves the “experimental” stage — my pragmatic choice is to continue with Jest in active projects.</p><h3>Final Thoughts &amp; Outlook</h3><p>Angular’s deprecation of Karma marks a pivotal shift — moving away from a once-default testing stack to a more modern, performance-oriented future. <strong>Vitest</strong> is the clear candidate for tomorrow, but today, many teams will stick with the tools they trust. For me, that means <strong>staying with Jest</strong> until Angular finalizes its official guidance.</p><p>It will be exciting to see whether Angular doubles down on Vitest, improves migration tooling, or introduces additional runners in the next releases. Until then, the key is consistency: use what your team knows best, and be ready to adapt when the dust settles.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cafe3f80115e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-unit-testing-in-v20-x-choosing-the-right-test-runner-cafe3f80115e">Angular Unit Testing in v20.x: Choosing the Right Test Runner</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Angular Material Tables: State Management Without the Mess]]></title>
            <link>https://javascript.plainenglish.io/simplifying-angular-material-tables-state-management-without-the-mess-a66ca3795e8e?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a66ca3795e8e</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-atelier]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[angular-material]]></category>
            <category><![CDATA[ngrx-signalstore]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 00:52:11 GMT</pubDate>
            <atom:updated>2025-08-15T00:52:11.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riWItd2SsoSmignH3fy4UA.png" /></figure><h3>The problem you’ve probably shipped already</h3><p>I keep seeing the same pattern in Angular apps: a Material mat-table whose component file quietly grows past 300 lines. It works fine at first. Then sorting, filtering, server-side pagination, and loading indicators creep in. The HTML is already noisy; the TypeScript becomes a catch-all for UI state, business rules, and HTTP calls. You now have a mini-feature framework living inside one component.</p><h3>Why that feels fine — until it isn’t</h3><p>Packing everything into the component optimizes for speed today, not change tomorrow. The costs show up later:</p><ul><li><strong>Mixed concerns:</strong> render logic, request orchestration, and domain decisions blur together.</li><li><strong>State sprawl:</strong> page index here, sort direction there, filters somewhere else.</li><li><strong>Negative reuse:</strong> a second table means copy-paste or yet another bespoke abstraction.</li></ul><p>If your table is trivial, keep it simple. But once you add any combination of server-side params, persisted filters, user-configurable columns, or row selection, the component becomes the wrong home for that logic.</p><h3>Today I want to show how NgRx SignalStore can solve it in an elegant way.</h3><ul><li>State and actions live together in one feature-focused store</li><li>Angular Signals make template consumption straightforward (no extra selector boilerplate)</li><li>The store stays testable, composable, and scoped to just this feature — not your whole app</li></ul><h3>Example of the problem</h3><p>A common pre-store implementation keeps <em>all</em> state, orchestration, and UI flags inside a single component:</p><pre>import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;<br>import { MatPaginator, PageEvent } from &#39;@angular/material/paginator&#39;;<br>import { MatSort, Sort } from &#39;@angular/material/sort&#39;;<br>import { TicketOrderService } from &#39;../services/ticket-order.service&#39;;<br>import { TicketOrder, TicketOrderResponse } from &#39;../models/ticket-order.model&#39;;<br>import { Paged } from &#39;../models/paged.model&#39;;<br><br>@Component({<br>  selector: &#39;app-ticket-order-overview&#39;,<br>  imports: [...]<br>  templateUrl: &#39;./ticket-order-overview.component.html&#39;,<br>  styleUrls: [&#39;./ticket-order-overview.component.scss&#39;]<br>})<br>export class TicketOrderOverviewComponent implements OnInit {<br>  protected readonly displayedColumns: string[] = [<br>    &#39;name&#39;, &#39;firstName&#39;, &#39;showDateTime&#39;, <br>    &#39;numberOfTickets&#39;, &#39;childrenTickets&#39;, &#39;nationalityCode&#39;<br>  ];<br><br>  protected ticketOrderResponsePage: Paged&lt;TicketOrderResponse&gt; | null = null;<br>  protected isLoading = false;<br>  protected hasLoadingError = false;<br><br>  protected sortKey: keyof TicketOrder = &#39;showDateTime&#39;;<br>  protected sortDirection: &#39;asc&#39; | &#39;desc&#39; = &#39;asc&#39;;<br>  protected pageIndex = 0;<br>  protected pageSize = 10;<br><br>  protected paginator = viewChild(MatPaginator);<br>  protected sort = viewChild(MatSort);<br><br>  private readonly ticketOrderService = inject(TicketOrderService)<br><br>  protected ngOnInit(): void {<br>    this.loadTicketOrders();<br>  }<br><br>  protected loadTicketOrders(): void {<br>    this.isLoading = true;<br>    this.hasLoadingError = false;<br><br>    this.ticketOrderService<br>      .getPagedTicketOrders(<br>        this.sortKey,<br>        this.sortDirection,<br>        this.pageIndex,<br>        this.pageSize<br>      ).subscribe({<br>        next: (page) =&gt; {<br>          this.ticketOrderResponsePage = page;<br>          this.isLoading = false;<br>        },<br>        error: (err) =&gt; {<br>          console.error(err);<br>          this.hasLoadingError = true;<br>          this.isLoading = false;<br>        }<br>      });<br>  }<br><br>  protected onPageChange(event: PageEvent): void {<br>    this.pageIndex = event.pageIndex;<br>    this.pageSize = event.pageSize;<br>    this.loadTicketOrders();<br>  }<br><br>  protected onSortChange(event: Sort): void {<br>    this.sortKey = event.active as keyof TicketOrder;<br>    this.sortDirection = event.direction || &#39;asc&#39;;<br>    this.pageIndex = 0;<br>    this.loadTicketOrders();<br>  }<br>}</pre><pre>&lt;table<br>  mat-table<br>  [dataSource]=&quot;ticketOrderResponsePage&quot;<br>  matSort<br>  [matSortActive]=&quot;sortKey&quot;<br>  [matSortDisableClear]=&quot;true&quot;<br>  [matSortDirection]=&quot;sortDirection&quot;<br>  (matSortChange)=&quot;onSortChange($event)&quot;<br>&gt;<br>  ...<br>&lt;/table&gt;<br>&lt;mat-paginator<br>  [length]=&quot;ticketOrderResponsePage?.totalItems&quot;<br>  [pageSize]=&quot;pageSize&quot;<br>  [pageSizeOptions]=&quot;[5, 10, 20, 100]&quot;<br>  [pageIndex]=&quot;pageIndex&quot;<br>  (page)=&quot;onPageChange($event)&quot;<br>&gt;&lt;/mat-paginator&gt;</pre><h3>Refactoring to NgRx SignalStore</h3><p>We move table-related state and orchestration into a feature-scoped store. This keeps the component focused on rendering and emitting user intents.</p><pre>import { Sort, SortDirection } from &#39;@angular/material/sort&#39;;<br>import { patchState, signalStore, withHooks, withMethods, withState } from &#39;@ngrx/signals&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { TicketOrdersService } from &#39;../../../core/services/ticket-orders.service&#39;;<br>import { rxMethod } from &#39;@ngrx/signals/rxjs-interop&#39;;<br>import { distinctUntilChanged, pipe, switchMap, tap } from &#39;rxjs&#39;;<br>import { TicketOrder, TicketOrderResponse } from &#39;../../../core/models/ticket-order.model&#39;;<br>import { Paged } from &#39;../../../core/models/paged.model&#39;;<br><br>interface State {<br>  ticketOrderResponsePage: Paged&lt;TicketOrderResponse&gt; | null;<br>  isLoading: boolean;<br>  hasLoadingError: boolean;<br>  query: Query;<br>}<br><br>interface Query {<br>  sortKey: keyof TicketOrder;<br>  sortDirection: SortDirection;<br>  pageIndex: number;<br>  pageSize: number;<br>}<br><br>const initialState: State = {<br>  ticketOrderResponsePage: null,<br>  isLoading: false,<br>  hasLoadingError: false,<br>  query: {<br>    sortKey: &#39;showDateTime&#39;,<br>    sortDirection: &#39;asc&#39;,<br>    pageIndex: 0,<br>    pageSize: 10,<br>  },<br>};<br><br>export const TicketOrderOverviewStore = signalStore(<br>  { providedIn: &#39;root&#39; },<br>  withState(initialState),<br>  withMethods((store, ticketOrderService = inject(TicketOrdersService)) =&gt; ({<br>    updatePageIndex(pageIndex: number, pageSize: number): void {<br>      patchState(store, (state) =&gt; ({ <br>        query: { ...state.query, pageIndex, pageSize }<br>      }));<br>    },<br>    updateSort(sort: Sort): void {<br>      const sortDirection = sort.direction;<br>      const sortKey = sort.active as keyof TicketOrder;<br>      patchState(store, (state) =&gt; ({<br>        query: { ...state.query, sortDirection, sortKey, pageIndex: 0 }<br>      }));<br>    },<br>    loadByQuery: rxMethod&lt;Query&gt;(<br>      pipe(<br>        distinctUntilChanged(),<br>        tap(() =&gt; patchState(store, { isLoading: true })),<br>        switchMap((query) =&gt; ticketOrderService.getPagedTicketOrders(query)<br>        tap({<br>              next: (ticketOrderResponsePage) =&gt; patchState(store, { ticketOrderResponsePage }),<br>              error: (error) =&gt; patchState(store, { hasLoadingError: true }),<br>              finalize: () =&gt; patchState(store, { isLoading: false }),<br>            }),<br>        ),<br>      ),<br>    ),<br>  }))<br>);</pre><h3>Wire up the component to the store</h3><p>The component gets thinner. It declares columns and forwards user actions to store methods.</p><pre>import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;<br>import { MatPaginator, PageEvent } from &#39;@angular/material/paginator&#39;;<br>import { MatSort, Sort } from &#39;@angular/material/sort&#39;;<br>import { TicketOrderService } from &#39;../services/ticket-order.service&#39;;<br>import { TicketOrder, TicketOrderResponse } from &#39;../models/ticket-order.model&#39;;<br>import { Paged } from &#39;../models/paged.model&#39;;<br><br>@Component({<br>  selector: &#39;app-ticket-order-overview&#39;,<br>  imports: [...]<br>  templateUrl: &#39;./ticket-order-overview.component.html&#39;,<br>  styleUrls: [&#39;./ticket-order-overview.component.scss&#39;]<br>})<br>export class TicketOrderOverviewComponent implements OnInit {<br>  protected readonly displayedColumns: string[] = [<br>    &#39;name&#39;, &#39;firstName&#39;, &#39;showDateTime&#39;, <br>    &#39;numberOfTickets&#39;, &#39;childrenTickets&#39;, &#39;nationalityCode&#39;<br>  ];<br><br>  protected readonly store = inject(TicketOrderOverviewStore);<br><br>  protected ngOnInit(): void {<br>    this.store.loadByQuery(this.store.query());<br>  }<br>}</pre><pre>&lt;table<br>  mat-table<br>  [dataSource]=&quot;store.ticketOrderResponsePage()&quot;<br>  matSort<br>  [matSortActive]=&quot;store.query().sortKey&quot;<br>  [matSortDisableClear]=&quot;true&quot;<br>  [matSortDirection]=&quot;store.query().sortDirection&quot;<br>  (matSortChange)=&quot;store.updateSort($event)&quot;<br>&gt;<br>  ...<br>&lt;/table&gt;<br>&lt;mat-paginator<br>  [length]=&quot;store.ticketOrderResponsePage()?.totalItems&quot;<br>  [pageSize]=&quot;store.query().pageSize&quot;<br>  [pageSizeOptions]=&quot;[5, 10, 20, 100]&quot;<br>  [pageIndex]=&quot;store.query().pageIndex&quot;<br>  (page)=&quot;store.updatePageIndex($event.pageIndex, $event.pageSize)&quot;<br>&gt;&lt;/mat-paginator&gt;</pre><h3><strong>The Result</strong><br> The component is now thin and declarative — it only defines the columns and delegates user actions to the store.</h3><p>All table state, data loading, and error handling are centralized in the SignalStore. Thanks to rxMethod, data loading runs automatically whenever the query signal changes.</p><p>This approach scales naturally:</p><ul><li>Components stay focused on rendering.</li><li>State remains testable and composable.</li><li>New table features don’t bloat the UI layer.</li></ul><p>You end up with a cleaner separation of concerns, less boilerplate, and a UI that’s easier to maintain as requirements grow.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a66ca3795e8e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/simplifying-angular-material-tables-state-management-without-the-mess-a66ca3795e8e">Simplifying Angular Material Tables: State Management Without the Mess</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Should You Use NgRx SignalStore’s Events Plugin?]]></title>
            <link>https://javascript.plainenglish.io/when-should-you-use-ngrx-signalstores-events-plugin-3a8eee3f4202?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a8eee3f4202</guid>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular-atelier]]></category>
            <category><![CDATA[ngrx-signalstore]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 17:31:42 GMT</pubDate>
            <atom:updated>2025-08-12T23:32:42.170Z</atom:updated>
            <content:encoded><![CDATA[<p>NgRx Signals is emerging as a modern, lightweight alternative to traditional state management in Angular, centered around Angular Signals. Compared to NgRx Store, it favors simplicity, fine-grained reactivity, and type safety. But while the core SignalStore handles localized state well, more complex applications often demand coordination, decoupling, and side-effect orchestration. This is where the experimental <strong>Events plugin</strong> enters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgbtG1Q82fpeeJ2_FKYY1g.jpeg" /></figure><h3>Why Add Another Layer to SignalStore?</h3><p>Angular and SignalStore already offer multiple ways to manage state. So why introduce an event-based layer?</p><p>The Events plugin decouples <em>what happened</em> (an event) from <em>what should change</em> (a reducer or effect). This separation provides:</p><ul><li><strong>Predictable data flow</strong> through unidirectional state updates.</li><li><strong>Decoupled communication</strong> between different stores or services.</li><li><strong>Testable and declarative logic</strong>, since reducers and effects react to known event types.</li></ul><p>The plugin introduces a layer of indirection, but the boilerplate is minimal compared to traditional NgRx Store — more than Signals alone, but less than full-blown Actions + Effects.</p><h3>Architectural Overview</h3><p>The plugin introduces a unidirectional data flow with four roles:</p><ul><li><strong>Event</strong>: A plain object representing a domain-specific occurrence.</li><li><strong>Dispatcher</strong>: A central service that routes events to handlers.</li><li><strong>Store</strong>: Hosts reducers and effects that respond to events and manage state.</li><li><strong>View Layer</strong>: Dispatches events and consumes state via signals.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*ZZKmnOkd_GtOIjXm.png" /><figcaption>Source: <a href="https://ngrx.io/guide/signals/signal-store/events">https://ngrx.io/guide/signals/signal-store/events</a></figcaption></figure><p>This structure closely mirrors Redux and NgRx Store. However, unlike NgRx Effects, effects here are scoped to stores, not global singletons. This allows for better modularity but also introduces potential duplication if not managed well.<br>For example, if multiple stores perform similar effects (like logging or analytics), you may end up duplicating handlers instead of reusing a shared effect. This is where Store Features come into play — allowing reuse and composition. We’ll cover that in a follow-up post. For now, let’s stay focused on the Events plugin.</p><h3>Defining Events: event and eventGroup</h3><p>The plugin provides two utilities for defining events:</p><ul><li>event: Defines a single event type and optional payload.</li></ul><pre>const opened = event(&#39;[Book Search Page] Opened&#39;);<br>const queryChanged = event(&#39;[Book Search Page] Query Changed&#39;, type&lt;string&gt;());</pre><p>Follow the [Source] EventName convention for clarity and tooling support.</p><ul><li>eventGroup: Consolidates related events under a shared source label.</li></ul><pre>const bookSearchEvents = eventGroup({<br>  source: &#39;Book Search Page&#39;,<br>  events: {<br>    opened: empty(),<br>    queryChanged: type&lt;string&gt;(),<br>  },<br>});</pre><p>The benefit of eventGroup is mainly organizational. If you find yourself repeating event source prefixes, consider using it.</p><h3>Updating State with Reducers</h3><p>State changes are defined via the withReducer plugin and the on function:</p><pre>withReducer((store) =&gt; store.on(bookSearchEvents.opened, (event, state) =&gt; ({<br>  isLoading: true,<br>})));</pre><p>Reducers can return an array mixing partial states and updater functions, allowing for sequential state mutations.</p><pre>const opened = event(&#39;[Book Search Page] Opened&#39;);<br>const queryChanged = event(&#39;[Book Search Page] Query Changed&#39;, type&lt;string&gt;());<br><br>export const BookSearchStore = signalStore(<br>  withState({ isLoading: false, query: &#39;&#39; }),<br>  withReducer(<br>    // Use a PartialStateUpdater to encapsulate loading logic<br>    on(opened, () =&gt; setLoading(true)),<br><br>    // Use array of updaters: update query, then set loading<br>    on(queryChanged, (event) =&gt; [<br>      setQuery(event.payload),<br>      setLoading(true),<br>    ]),<br>  ),<br>);<br><br>// 👇 Reusable state updater for setting isLoading<br>function setLoading(value: boolean): PartialStateUpdater&lt;{ isLoading: boolean }&gt; {<br>  return (state) =&gt; ({ isLoading: value });<br>}<br><br>// 👇 Reusable state updater for setting the query<br>function setQuery(query: string): PartialStateUpdater&lt;{ query: string }&gt; {<br>  return (state) =&gt; ({ query });<br>}</pre><h3>Handling Side Effects with Effects</h3><p>For side effects like HTTP calls or logging, use withEffects:</p><pre>withEffects(({ on }) =&gt; on(bookSearchEvents.queryChanged).pipe(<br>  switchMap(({ payload }) =&gt; this.booksService.search(payload).pipe(<br>    map(data =&gt; booksApiEvents.loadedSuccess(data)),<br>    catchError(() =&gt; of(booksApiEvents.loadedFailure()))<br>  ))<br>));</pre><p>Key points</p><ul><li>Effects are scoped to their store.</li><li>Return values that are events are re-dispatched automatically.</li><li>You can’t dispatch arbitrary actions — only events — preserving the event-driven purity.</li></ul><p>This design is both a strength and a limitation: it enforces discipline but restricts flexibility compared to something like plain RxJS in a service.</p><h3>Dispatching Events</h3><p>You can dispatch events manually:</p><pre>this.dispatcher.dispatch(bookSearchEvents.opened());</pre><p>Or use injectDispatch for syntactic sugar:</p><pre>readonly dispatch = injectDispatch(bookSearchEvents);<br>this.dispatch.queryChanged(&#39;Angular&#39;);</pre><p>The latter reduces boilerplate, especially in components, but it adds magic. Some developers might prefer explicitness over this convenience.</p><h3>Reading State: Nothing Changes</h3><p>The Events plugin doesn’t alter how state is exposed:</p><pre>this.store.query(); // Signal<br>this.store.books(); // Signal</pre><p>This consistency is a good thing. Your state remains signal-based and accessible as before.</p><h3>When Should You Use It?</h3><p>The Events plugin introduces structure — but at the cost of added complexity. It’s worth considering in the following scenarios:</p><ul><li><strong>Coordinated Reactions Across Multiple Stores</strong>: Imagine a user clicks “Add to Cart.” The cart store needs to add the item, the product store should update stock, and the analytics store logs the action. With shared events, each store listens to the same itemAdded event, enabling clean separation without chaining service calls or duplicating logic.</li><li><strong>Modular and Testable Side Effects</strong>: Suppose changing a search query triggers a debounce, a backend request, and a fallback if offline. With effects scoped to the store, you can isolate and test this behavior without relying on external services, improving reliability and reuse.</li><li><strong>Scalable, Maintainable Architecture</strong>: In a large application with multiple teams working on different features, using events enforces consistent patterns. For example, the same userLoggedOut event can trigger cleanup in auth, clear caches in data stores, and redirect the user—without requiring cross-service dependencies.</li></ul><p>But for small apps or isolated state concerns, vanilla SignalStore (or even just Angular Signals + services) might be sufficient.</p><h3>Final Thoughts</h3><p>NgRx SignalStore’s Events plugin is a step toward structured, scalable architecture in Angular, blending the power of Signals with lessons from the Flux and NgRx ecosystems. It’s not a one-size-fits-all solution. Used judiciously, it can add clarity and modularity. Overused, it can drown you in ceremony.</p><p>It’s still marked experimental — expect changes. But it’s a clear signal (pun intended) of where Angular state management is heading: less RxJS boilerplate, more fine-grained reactivity, and greater architectural discipline.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a8eee3f4202" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/when-should-you-use-ngrx-signalstores-events-plugin-3a8eee3f4202">When Should You Use NgRx SignalStore’s Events Plugin?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking Angular’s v20 Style Guide: A New Compass or a Loose Map?]]></title>
            <link>https://medium.com/@e.kapprafael/rethinking-angulars-v20-style-guide-a-new-compass-or-a-loose-map-4cf408829cb8?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf408829cb8</guid>
            <category><![CDATA[angular-atelier]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 07:46:36 GMT</pubDate>
            <atom:updated>2025-07-31T07:46:36.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-XM0N_RTYXPJvKYjG_Ejw.png" /><figcaption>Generated With AI From The Autor</figcaption></figure><h3><strong>Angular just got a new style guide in v20 — and it’s not what I expected.</strong></h3><p>I’ve been around long enough to remember when Angular projects felt like the wild west. Teams did whatever made sense to them, and chaos often followed. Even in the AngularJS days, we <em>tried</em> to keep things consistent, but it wasn’t until <a href="https://github.com/johnpapa/angular-styleguide">John Papa published his style guide</a> that we finally had shared structure.</p><p>That guide wasn’t perfect, but it was transformative. It turned tacit knowledge into explicit patterns. It wasn’t just opinionated — it was practical. Then came Angular 2+ with its completely new mental model, and John Papa adapted again. His Angular style guide was integrated into the official docs and became the de facto reference for many teams.</p><p>But then? Almost a decade of stagnation. The guide remained mostly static — even as Angular itself evolved dramatically.</p><h3>The v20 Style Guide: What Changed</h3><p>With Angular 20, the team has finally dropped a fresh style guide. But this time, it’s different — not just in content, but in philosophy. It’s leaner, less prescriptive, and more reflective of current patterns. That’s good in some ways. But it also leaves more open questions.</p><p>Let’s break down some of the major changes — and what they might mean.</p><h4>Prefer inject() Over Constructor Injection</h4><p>Old Way:</p><pre>constructor(private router: Router) {}</pre><p>New Way:</p><pre>const router = inject(Router);</pre><p>The new guide recommends using inject()—and I fully agree. It reduces constructor clutter, improves readability, and simplifies testing. It also makes inheritance less painful, since you no longer have to pass dependencies through parent constructors.</p><p>That said, I generally avoid inheritance in Angular and prefer composition. But in the rare cases where inheritance is used (like abstract base components), inject() removes one of the major friction points.</p><p>Constructor injection was useful when tooling was limited, but today, inject() is cleaner, more flexible, and better aligned with how modern Angular apps are built.</p><h4>Use protected for Template-Only Members</h4><pre>protected isLoggedIn = signal(false);</pre><p>This is a solid refinement. It makes it clear what is internal to the template and not part of the component’s public API. That clarity improves maintainability.</p><p>No real downside here, though I’d like to see the guide acknowledge that protected vs public isn&#39;t enforced at runtime, and some teams may find this distinction too subtle to matter. Still, this change feels like progress.</p><h4>Use readonly for Angular-Initialized Properties</h4><pre>readonly productId = input&lt;string&gt;();</pre><p>This is another good practice that many teams already follow. It helps avoid accidental reassignment of values that Angular owns.</p><p>That said, the guide doesn’t address edge cases where mutation might be necessary or where readonly complicates dynamic logic. A little nuance here would go a long way.</p><h4>Prefer [class] and [style] Bindings Over ngClass and ngStyle</h4><pre>&lt;div [class.active]=&quot;isActive&quot; [style.color]=&quot;color&quot;&gt;Hello&lt;/div&gt;</pre><p>This one is interesting. It aligns with the general trend toward more explicit, analyzable templates. [class.foo] is easier for tooling and arguably easier for humans to scan at a glance.</p><p>But ngClass and ngStyle are powerful because they let you express conditional styling concisely. If overused, yes, they reduce readability—but that’s true of any tool. The style guide seems to favor minimalism over expressive power here. Is that a universal win? I&#39;m not sure.</p><h4>No More .component.ts or .service.ts Suffixes?</h4><p>Here’s where I’m not on board.</p><p>The new guide implies — through its examples — that we should stop naming files like product.component.ts or auth.service.ts. Instead, just call them product.ts, auth.ts, etc.</p><p>This is a <em>massive</em> shift, and the rationale isn’t explained. In fact, it’s not even explicitly stated — it’s implied through omission. That’s a problem.</p><p>These suffixes aren’t just convention. They’re functional. They make it immediately obvious what a file contains. They work with IDE tooling, they improve searchability, and they align with conventions in other frameworks (e.g., .test.js, .module.css).</p><p>Removing them might make filenames shorter — but at what cost? In a large codebase, product.ts tells me nothing. Is it a component? A model? A service? The suffix clarifies that instantly.</p><p>If the Angular team wants to deprecate this convention, they need to make the case. Right now, it feels like erosion of a good idea without a compelling reason.</p><h3>My Take: Structure vs. Flexibility</h3><p>When I first read the new style guide, I was conflicted. It’s shorter. Simpler. Less rigid.</p><p>I missed the structure. I missed the rules. But the more I thought about it, the more I realized: <em>that’s the point.</em></p><p>The Angular ecosystem today is more diverse than it was in 2015. Teams use Nx, Signals, Tailwind, Storybook, NgRx, and standalone APIs. There’s no longer one canonical way to structure an Angular app. And maybe there shouldn’t be.</p><p>The new guide accepts that reality. It doesn’t try to enforce a single path. It offers patterns, not prescriptions. That’s useful — but it also places more responsibility on teams to define their own structure.</p><p>If your team needs strong conventions, this guide won’t give you enough. If your team thrives on flexibility, this guide will get out of your way.</p><h3>Final Thoughts</h3><p>The Angular v20 style guide isn’t just a documentation update — it’s a cultural shift. It acknowledges how Angular development has changed and steps back to let teams adapt.</p><p>But with that freedom comes risk. Without strong defaults, consistency becomes a team-by-team effort. That might be the right call in 2025 — but it’s a far cry from the structured clarity of the John Papa era.</p><p>Whether you see this as evolution or erosion probably depends on what you value more: flexibility or convention.</p><p>Either way, the compass has changed. Just make sure your team is holding the same map.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf408829cb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signals vs. RxJS: Understanding Angular’s Dual Approach to Reactivity]]></title>
            <link>https://javascript.plainenglish.io/signals-vs-rxjs-understanding-angulars-dual-approach-to-reactivity-259411e9d40d?source=rss-43dad64495d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/259411e9d40d</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular-atelier]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Rafael Kapp]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 11:18:44 GMT</pubDate>
            <atom:updated>2025-08-14T00:09:41.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoUne6-qxJ2EY5H0_hnDrQ.png" /></figure><p>Angular has long relied on RxJS for managing asynchronous events, handling race conditions, and coordinating complex data flows. However, with the introduction of Angular Signals, the framework is offering a new primary basic reactive building block, providing an alternative to RxJS for simpler reactivity needs. While some might question why Angular would introduce a new system when RxJS and BehaviorSubject already exist, Signals offer distinct advantages, particularly for basic reactive operations.</p><h3>Signals as the Basic Reactive Building Block</h3><p>At its core, a <strong>signal</strong> in Angular is a wrapper around a value that notifies interested consumers when that value changes. Signals can hold any value, from primitives to complex data structures, and their value is read by calling them as getter functions. Writable signals, created with the signal() function, allow direct updates via .set() or .update() methods.</p><p>For deriving values from other signals, <strong>computed signals</strong> are used. They are read-only and define a derivation function that automatically re-evaluates when their dependencies change. A key benefit of computed signals is their <strong>lazy evaluation and memoization</strong>: the derivation function only runs when the computed signal is first read, and its value is cached until a dependency changes. This makes them suitable for computationally expensive derivations.</p><p>Here’s how computed signals handle multiple simultaneous changes in a clean, predictable way:</p><pre>import { signal, computed } from &#39;@angular/core&#39;;<br><br>// A writable signal holding a numeric counter<br>const count = signal(0);<br><br>// A computed signal that derives a value from `count`<br>const doubled = computed(() =&gt; count() * 2);<br><br>// Reading and updating signals<br>console.log(doubled()); // 0<br>count.set(2);<br>console.log(doubled()); // 4</pre><p>One of the most compelling arguments for Signals as a basic reactive building block, especially when compared to RxJS’s BehaviorSubject, lies in their simplicity and predictability.</p><h4>Easier Access and No Manual Subscriptions</h4><p>With Signals, accessing values (e.g., in a component class) is direct, simply by calling the signal function (e.g., count()). When working with RxJS, especially after piping operations, a BehaviorSubject becomes a standard Observable, necessitating subscriptions and proper unsubscription strategies to prevent memory leaks or unwanted behavior. Signals inherently manage their subscriptions within Angular&#39;s reactivity system, eliminating the need for manual cleanup in most cases.<br>Compare this with a similar setup using RxJS, where you need to manage subscriptions manually:</p><pre>import { BehaviorSubject } from &#39;rxjs&#39;;<br><br>// With RxJS<br>const count$ = new BehaviorSubject(0);<br><br>// Reading the current value (not reactive)<br>console.log(count$.getValue());<br><br>// Subscribing<br>const subscription = count$.subscribe(value =&gt; {<br>  console.log(&#39;Count is&#39;, value);<br>});<br>count$.next(2);<br><br>// Cleanup is manual<br>subscription.unsubscribe();</pre><h4>Glitch-Free Computation</h4><p>When combining multiple reactive values, computed signals provide a &quot;glitch-free computation.&quot; This means that if multiple dependent signals update simultaneously, a computed signal will only emit its final, correct value, avoiding intermediate, potentially incorrect &quot;transitory&quot; values that can occur with RxJS&#39;s combineLatest in certain scenarios.</p><p>This example shows how computed signals evaluate cleanly even when multiple dependencies change at once</p><pre>const first = signal(1);<br>const second = signal(2);<br><br>const sum = computed(() =&gt; first() + second());<br><br>effect(() =&gt; {<br>  console.log(&#39;Sum:&#39;, sum());<br>});<br><br>// Update both synchronously<br>first.set(3);<br>second.set(4);<br><br>// Effect only runs once with Sum: 7</pre><p>Even though both source signals change, the effect runs only once with the final sum, avoiding ‘glitches’ common in combineLatest.</p><h4>Simplified Side Effects</h4><p>Effects in Signals, created with the effect() function, run whenever one or more signal values they read change. They are useful for syncing data with localStorage, custom DOM behavior, or logging, but should generally be avoided for propagating state changes. Importantly, an effect only runs if the signal&#39;s value actually changes, not just if it&#39;s set to the same value again. This contrasts with tap() or manual RxJS subscriptions, which can trigger side effects unexpectedly if an observable is subscribed to multiple times.</p><p>Here’s how an effect tracks changes to a signal and only runs when its value truly changes:</p><pre>const username = signal(&#39;rafael&#39;);<br><br>effect(() =&gt; {<br>  console.log(&#39;Username changed to:&#39;, username());<br>});<br><br>username.set(&#39;rafael&#39;); // No effect, same value<br>username.set(&#39;kapp&#39;);   // Triggers effect</pre><p>The simplicity and directness of Signals make Angular less “hostile to beginners” and more accessible to developers who are not deeply familiar with complex RxJS concepts.</p><h3>Advanced Reactive Patterns with Signals</h3><p>Beyond basic state management, Angular Signals introduce powerful functions for handling more complex reactive scenarios: linkedSignal for dependent state and resource for asynchronous reactivity (this is still experimental).</p><h4>Dependent State</h4><p>Often, a piece of application state depends on another signal, and if the source signal changes, the dependent state might become invalid. The linkedSignal function addresses this by creating a signal that is intrinsically linked to some other state.</p><p>Instead of a default value, linkedSignal takes a <strong>computation function</strong> (similar to computed). This function ensures that the linkedSignal always has a valid value, even if its source changes. For example, if a selectedOption signal defaults to the first item in a shippingOptions signal, linkedSignal ensures selectedOption updates if shippingOptions itself changes.</p><p>With linkedSignal, you can easily create state that responds to changes in other signals. Here&#39;s a realistic example involving shipping options:</p><pre>const shippingOptions = signal([&#39;Standard&#39;, &#39;Express&#39;]);<br>const selectedOption = linkedSignal({<br>  source: shippingOptions,<br>  compute: (options) =&gt; options.includes(&#39;Express&#39;) ? &#39;Express&#39; : options[0],<br>});<br><br>console.log(selectedOption()); // Express<br>shippingOptions.set([&#39;Standard&#39;]); // selectedOption updates to &#39;Standard&#39;</pre><p>For more advanced scenarios, linkedSignal can be configured with separate source and computation properties. The source is any signal, and its changes trigger the computation. The computation function receives the new value of the source and a previous object (previous.source, previous.value). This allows preserving previous user selections if they are still valid within the new source data, otherwise defaulting to a fallback.</p><p>Like other signals, linkedSignal can also be configured with a <strong>custom equality function</strong> (equal option) to determine when its value (the result of the computation) has truly changed, preventing unnecessary updates for downstream dependencies. By default, signals use referential equality.</p><h3>RxJS Interoperability: A Harmonious Coexistence</h3><p>It’s important to understand that Angular Signals are not meant to replace RxJS entirely. Instead, they provide an efficient and simpler solution for basic reactive building blocks, while <strong>seamlessly interoperating</strong> with RxJS where more complex asynchronous data flows are still best handled by observables. The @angular/rxjs-interop package facilitates this integration.</p><h4>toSignal()</h4><p>This function allows you to create a signal that tracks the value of an RxJS Observable. It behaves similarly to Angular&#39;s async pipe but offers greater flexibility. toSignal subscribes to the Observable immediately and automatically unsubscribes when the component or service that created it is destroyed. It can be configured with an initialValue for Observables that don&#39;t emit synchronously, or requireSync: true for those that do (like BehaviorSubject). If the Observable errors, the signal will throw that error when read; if it completes, the signal retains its last value.</p><h4>toObservable()</h4><p>Conversely, toObservable() allows you to create an RxJS Observable that tracks the value of a signal. It uses an effect internally to monitor the signal&#39;s value and emit it to the Observable when it changes. Notably, toObservable will only emit the signal&#39;s value after it stabilizes, meaning multiple synchronous signal updates will result in only the last value being emitted by the observable.</p><p>Finally, here’s how you can bridge RxJS and Signals using the toSignal() and toObservable() utilities:</p><pre>import { toSignal, toObservable } from &#39;@angular/core/rxjs-interop&#39;;<br>import { interval } from &#39;rxjs&#39;;<br><br>// RxJS to Signal<br>const clock$ = interval(1000);<br>const clockSignal = toSignal(clock$, { initialValue: 0 });<br><br>effect(() =&gt; {<br>  console.log(&#39;Tick:&#39;, clockSignal());<br>});<br><br>// Signal to RxJS<br>const name = signal(&#39;Rafael&#39;);<br>const name$ = toObservable(name);<br><br>name$.subscribe(value =&gt; console.log(&#39;Name:&#39;, value));<br>name.set(&#39;Kapp&#39;);</pre><p>Furthermore, Angular provides utilities for component outputs: outputFromObservable allows creating a component output that emits based on an RxJS observable, and outputToObservable creates an RxJS observable from an existing component output.</p><h3>Conclusion</h3><p>Angular Signals offer a powerful and intuitive system for managing reactive state, simplifying common patterns that previously required a deeper understanding of RxJS concepts. They address issues like manual subscription management, complex derived values, and subtle side effect traps. However, Signals do not diminish the role of RxJS. Instead, they focus on providing a more accessible foundation for reactivity, complementing RxJS for advanced asynchronous data streams and complex event handling. The rich interoperability APIs ensure that developers can leverage the strengths of both systems, creating robust, performant, and maintainable Angular applications. It’s not about choosing “either/or” but rather about understanding when to use each tool for the most effective outcome.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259411e9d40d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/signals-vs-rxjs-understanding-angulars-dual-approach-to-reactivity-259411e9d40d">Signals vs. RxJS: Understanding Angular’s Dual Approach to Reactivity</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>