<?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 Prashantsaransingh on Medium]]></title>
        <description><![CDATA[Stories by Prashantsaransingh on Medium]]></description>
        <link>https://medium.com/@prashantsaransingh?source=rss-4159ccff2619------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8cZQIC-kdND6edl3</url>
            <title>Stories by Prashantsaransingh on Medium</title>
            <link>https://medium.com/@prashantsaransingh?source=rss-4159ccff2619------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:31:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashantsaransingh/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[Angular Beyond Zone.js: A Complete Guide to Zoneless and Standalone Architecture]]></title>
            <link>https://medium.com/@prashantsaransingh/angular-beyond-zone-js-a-complete-guide-to-zoneless-and-standalone-architecture-eda1f520e71e?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda1f520e71e</guid>
            <category><![CDATA[angular-update]]></category>
            <category><![CDATA[optimise-web-pages]]></category>
            <category><![CDATA[angular-zoneless]]></category>
            <category><![CDATA[angular-21]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 07:31:51 GMT</pubDate>
            <atom:updated>2026-03-11T10:25:11.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvPROft7_2QlWqNYf5WpVg.png" /></figure><p>For over a decade, Angular developers have lived in a world of “automatic” magic. We changed a variable, and the UI updated. We clicked a button, and the screen refreshed. This magic was powered by <strong>Zone.js</strong>, a library that intercepted every asynchronous browser API to trigger change detection.</p><p>But the magic came at a cost: bundle size, execution overhead, and a “check everything” approach that didn’t scale perfectly for massive apps.</p><p>With Angular 18+, we have entered the <strong>Zoneless Era</strong>. By using provideZonelessChangeDetection(), we are removing the safety net of Zone.js. In this guide, we will explore how to navigate this shift, why NgModules are fading away, and how to keep your @Input properties working in a world without automatic cycles.</p><h3>1. The Core Shift: From “Global” to “Targeted”</h3><p>In a traditional <strong>Module-based</strong> application, Zone.js treats the component tree like a single entity. When an event occurs, it triggers a &quot;Top-Down&quot; scan. Even if only one small child component changed, Angular might still check the entire tree.</p><p>In a <strong>Zoneless</strong> architecture, that global trigger is gone. Angular now relies on components being <strong>“Dirty.”</strong></p><p><strong>The Result:</strong> Angular only visits the parts of the tree that specifically signaled they have new data. This makes your app incredibly snappy, but it requires you to be more intentional with your code.</p><h3>2. The Death of declarations and the Rise of Standalone</h3><p>If you are bootstrapping your application using the modern bootstrapApplication method, you are likely moving away from AppModule.</p><pre>// main.ts - The Modern Entry Point<br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideZonelessChangeDetection()<br>  ]<br>});</pre><p>In this setup, the concept of <strong>declarations: []</strong> is obsolete.</p><ul><li><strong>Locality of Reference:</strong> In a Standalone component, you import exactly what you need (other components, pipes, or modules) directly into the component decorator.</li><li>In the old NgModule days, if you declared 50 components in a module, they were often bundled together even if you only routed to one. Standalone components allow for superior <strong>Tree Shaking</strong>, significantly reducing your final JavaScript payload.</li></ul><h3>3. Will my @Input() still work?</h3><p>The short answer is <strong>yes</strong>, but with a massive catch.</p><p>In a Zoneless environment, a standard @Input() property is just a plain JavaScript variable. Changing that variable <strong>does not</strong> automatically tell Angular to re-render the component.</p><h4>The “Zoneless Failure” Example:</h4><p>Imagine you have a child component with a standard @Input():</p><pre>@Component({ ... })<br>export class UserProfileComponent {<br>  @Input() name: string = &#39;&#39;;<br>}</pre><p>If the parent updates name inside a setTimeout or an Observable subscription, <strong>the UI will not change.</strong> Why? Because Zone.js isn&#39;t there to notice the timer finished. The variable changed in memory, but the DOM stayed static.</p><h4>The Solution: Signal Inputs</h4><p>This is why <strong>Signal Inputs</strong> are the backbone of Zoneless Angular. They are “self-aware.”type</p><pre>// new Way<br>name = input&lt;string&gt;(&#39;&#39;); // returns an InputSignal</pre><p>When a Signal Input receives a new value, it automatically notifies the Angular scheduler: <em>“Hey, I have new data! Mark this component as dirty and include it in the next render cycle.”</em></p><h3>Summary: A Checklist for Success</h3><p>To successfully publish a Zoneless app today, follow these rules:</p><ul><li><strong>Bootstrap Standalone:</strong> Use bootstrapApplication and remove your AppModule.</li><li><strong>Enable Zoneless:</strong> Add provideZonelessChangeDetection() to your providers.</li><li><strong>Default to Standalone:</strong> Every new component should be standalone: true.</li><li><strong>Prefer Signal Inputs:</strong> Transition from @Input() to input() to ensure your components &quot;wake up&quot; when data arrives.</li><li><strong>Be Explicit:</strong> If you aren’t using signals, remember to use markForCheck() when updating data inside async operations.</li></ul><h3>Conclusion</h3><p>Going Zoneless isn’t just about deleting a library from your bundle. It’s about adopting a more modern, reactive mindset. By combining <strong>Standalone Components</strong> with <strong>Signals</strong>, you are building an application that is ready for the future of the web — faster, smaller, and infinitely more predictable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda1f520e71e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Zoneless and Signals in 2026]]></title>
            <link>https://medium.com/@prashantsaransingh/mastering-zoneless-and-signals-in-2026-2d4f9230a439?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4f9230a439</guid>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[angular-zoneless]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-update]]></category>
            <category><![CDATA[zoneless]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 12:12:32 GMT</pubDate>
            <atom:updated>2026-03-10T12:12:32.021Z</atom:updated>
            <content:encoded><![CDATA[<p>For a decade, Angular relied on zone.js to &quot;magically&quot; detect changes. But that magic came with a performance cost. In 2026, we have moved into the <strong>Zoneless Era</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*K62r9ALsSC3mi60NJtwehw.png" /></figure><h3>1. Zoneless Change Detection: The “Quiet” Revolution</h3><p>In Angular 21, Zoneless is now the <strong>default recommendation</strong> for high-performance apps.</p><h3>What it is:</h3><p>Zoneless removes the zone.js library, which previously patched every browser event (clicks, timers, HTTP) to trigger a global check.</p><ul><li><strong>The “Old” way:</strong> Angular checks the <em>entire</em> component tree whenever <em>anything</em> happens.</li><li><strong>The “Zoneless” way:</strong> Angular only checks the UI when a <strong>Signal</strong> updates or a specific event occurs.</li></ul><h3>How to enable it:</h3><p>You no longer need zone.js in your polyfills. Simply bootstrap your app like this:</p><pre>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideZonelessChangeDetection() // High performance, no zone.js needed<br>  ]<br>});</pre><p><strong>Impact:</strong> Bundle sizes drop by ~30kb, and “Time to Interactive” (TTI) improves because the browser doesn’t have to process the Zone overhead.</p><h3>2. Latest Signal Primitives: The 2026 Toolkit</h3><p>While signal(), computed(), and effect() are the basics, Angular 20 and 21 introduced advanced primitives that make RxJS unnecessary for 90% of standard UI logic.</p><h3>A. linkedSignal() – The Missing Link</h3><p>One of the most powerful additions in late 2025. It acts like a computed() signal but is <strong>writable</strong>.</p><ul><li><strong>Problem:</strong> You have a “Quantity” signal that needs to reset to 1 whenever the &quot;Product&quot; changes, but you also want the user to be able to manually change the &quot;Quantity.&quot;</li><li><strong>Solution:</strong> linkedSignal tracks the product and resets itself, but remains mutable by the user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9XJXADZpIxDiaXKt-2MnQ.png" /></figure><h3>B. resource() and httpResource() – Declarative Data Fetching</h3><p>These APIs are the “Signals” answer to HttpClient observables.</p><ul><li><strong>Reactive Fetching:</strong> If you have a signal userId(), and you use it inside an httpResource, Angular <strong>automatically</strong> re-fetches the data whenever the ID changes.</li><li><strong>Built-in States:</strong> It provides native signals for .isLoading(), .error(), and .value().</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*TCJUy197WOrD1wwW6pPDAg.png" /></figure><pre>userResource = httpResource(() =&gt; `/api/users/${this.userId()}`);</pre><pre>// In template:<br>@if(userResource.isLoading()) { &lt;spinner /&gt; }<br>@else { {{ userResource.value()?.name }} }</pre><h3>3. Signal-Based Forms (The v21 Game Changer)</h3><p>This is the “hottest” topic in 2026. Angular 21 introduced the experimental @angular/forms/signals package, which is set to replace ReactiveFormsModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KC421Wg4QnV0xSw_WQhJ9Q.png" /></figure><h3>Why it’s better:</h3><ul><li><strong>Direct Binding:</strong> The “form model” <em>is</em> a signal. When you update the signal, the form updates; when the user types, the signal updates.</li><li><strong>Strict Type Safety:</strong> Unlike old forms, Signal Forms infer types perfectly from your data object.</li><li><strong>No More Boilerplate:</strong> You don’t need FormGroup or FormControl classes. You just define a form() structure.</li></ul><pre>profileForm = form({<br>  name: signal(&#39;John Doe&#39;, { validators: [required] }),<br>  email: signal(&#39;&#39;, { validators: [email] })<br>});</pre><h3>4. Signal Queries &amp; Inputs (Now Stable)</h3><p>In early 2026, the old decorators @Input(), @Output(), @ViewChild(), and @ContentChild() are considered &quot;Legacy.&quot;</p><ul><li><strong>input()</strong>: Instead of @Input(), we use name = input&lt;string&gt;(). This returns a signal, meaning you can use it in a computed() without needing ngOnChanges.</li><li><strong>viewChild()</strong>: Returns a signal of the element. No more checking if the element exists in ngAfterViewInit—the signal handles the presence reactively.</li></ul><h3>5. Summary: Why This Matters for Your Article</h3><p>If you’re writing for Medium, focus on these <strong>three </strong>:</p><ul><li><strong>Developer Experience</strong>: Code is more readable. No more async pipes everywhere or BehaviorSubject madness.</li><li><strong>Performance</strong>: No global change detection “ticks.” The app is surgical — only updating exactly what changed.</li><li><strong>Future-Proofing</strong>: Angular is aligning with the native “Signals” standard being discussed for browsers.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4f9230a439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up a Reverse Proxy and Why You Need One]]></title>
            <link>https://medium.com/@prashantsaransingh/how-to-set-up-a-reverse-proxy-and-why-you-need-one-d8d6a8363ec3?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d6a8363ec3</guid>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 12:11:48 GMT</pubDate>
            <atom:updated>2026-03-11T07:36:30.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Reverse Proxy?</h3><p>Think of a reverse proxy as a <strong>concierge</strong> for your servers. When a user requests your website, they don’t talk directly to your application. Instead, they talk to the proxy, which then fetches the data from the backend and delivers it back to the user.</p><h3>Key Benefits</h3><ul><li><strong>Load Balancing:</strong> Evenly distributes traffic so no single server gets overwhelmed.</li><li><strong>SSL Termination:</strong> Centralizes your HTTPS certificates, freeing your backend from the heavy lifting of encryption.</li><li><strong>Anonymity:</strong> Hides your backend IP addresses, making it much harder for attackers to target your servers directly.</li><li><strong>Static Content Caching:</strong> Serves images and CSS directly from the proxy to speed up load times.</li></ul><h3>Setting Up an Apache Reverse Proxy on Ubuntu</h3><p>While Nginx is popular, <strong>Apache (httpd)</strong> remains a powerhouse for reverse proxying due to its robust module system. Follow these steps to set it up correctly on Ubuntu 24.04 (or 22.04).</p><h3>Step 1: Install and Enable Modules</h3><p>First, ensure Apache is installed and enable the specific modules required to pass traffic to a backend service.</p><pre>sudo apt update &amp;&amp; sudo apt install apache2 -y</pre><pre># Enable proxy modules<br>sudo a2enmod proxy<br>sudo a2enmod proxy_http<br>sudo a2enmod ssl<br>sudo a2enmod headers</pre><pre># Restart to apply changes<br>sudo systemctl restart apache2</pre><h3>Step 2: Configure the Virtual Host</h3><p>On Ubuntu, Apache configurations are stored in /etc/apache2/sites-available/. Avoid using httpd-ssl.conf unless you&#39;ve manually created it; it&#39;s better to use the standard Ubuntu directory structure.</p><p>Create a new config file for your site:sudo nano /etc/apache2/sites-available/my-app.conf</p><p><strong>Paste the following configuration:</strong><em>(Note: We use </em><em>Require all granted instead of the deprecated </em><em>Order allow,deny syntax).</em></p><pre>&lt;VirtualHost *:80&gt;<br>    ServerName your-domain.com<br>    # Redirect all HTTP traffic to HTTPS<br>    Redirect permanent / https://your-domain.com/<br>&lt;/VirtualHost&gt;</pre><pre>&lt;VirtualHost *:443&gt;<br>    ServerName your-domain.com<br>    ServerAdmin admin@your-domain.com</pre><pre>    SSLEngine on<br>    SSLCertificateFile /etc/ssl/certs/your-cert.pem<br>    SSLCertificateKeyFile /etc/ssl/private/your-key.pem</pre><pre>    # Proxy Settings<br>    ProxyPreserveHost On<br>    ProxyPass / <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a><br>    ProxyPassReverse / <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a></pre><pre>    # Security Headers<br>    RequestHeader set X-Forwarded-Proto &quot;https&quot;</pre><pre>    ErrorLog ${APACHE_LOG_DIR}/error.log<br>    CustomLog ${APACHE_LOG_DIR}/access.log combined<br>&lt;/VirtualHost&gt;</pre><h3>Step 3: Enable the Site and Test</h3><p>Now, tell Apache to start using your new configuration and check for syntax errors.</p><ul><li><strong>Enable the config:</strong> sudo a2ensite my-app.conf</li><li><strong>Disable the default:</strong> sudo a2dissite 000-default.conf (Optional)</li><li><strong>Test Syntax:</strong> sudo apache2ctl configtest</li><li><strong>Reload:</strong> sudo systemctl restart apache2</li></ul><h3>Troubleshooting Common Flaws</h3><p>If your proxy isn’t working, check these three things:</p><ul><li><strong>The Backend Port:</strong> Ensure your application (Node, Python, Go, etc.) is actually listening on 127.0.0.1:8080.</li><li><strong>Firewall:</strong> Ensure ports 80 and 443 are open: sudo ufw allow &#39;Apache Full&#39;.</li><li><strong>Permissions:</strong> Ensure your SSL certificate files are readable by the www-data user.</li></ul><h3>Conclusion</h3><p>By moving SSL termination and traffic management to an Apache reverse proxy, you’ve made your application more secure and easier to scale. This setup allows you to swap out backend services or add more servers in the future without ever changing how the user accesses your site.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d6a8363ec3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ng-template , ng-content , NgTemplateOutlet & ViewContainerRef in Angular]]></title>
            <link>https://medium.com/@prashantsaransingh/understanding-ng-template-in-angular-1875f10b13fe?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/1875f10b13fe</guid>
            <category><![CDATA[templateoutlet]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ng-container]]></category>
            <category><![CDATA[dynamic-template]]></category>
            <category><![CDATA[ng-template]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 12:33:17 GMT</pubDate>
            <atom:updated>2024-12-24T07:46:34.996Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular provides developers with tools to create powerful, dynamic, and reusable templates. One such tool is the &lt;ng-template&gt; element. Let’s dive into what it is, how it works, and how you can use it in your projects.</p><h3>What is ng-template ?</h3><p>&lt;ng-template&gt; defines a template that is not rendered by default. It is only rendered when explicitly instructed, giving you full control over when and how content is displayed.</p><p>For example, if you wrap content inside an &lt;ng-template&gt;, it won&#39;t appear on the page unless explicitly rendered:</p><pre>&lt;p&gt;Hello!&lt;/p&gt;<br>&lt;ng-template&gt;<br>  &lt;p&gt;Welcome!&lt;/p&gt;<br>&lt;/ng-template&gt;<br>&lt;p&gt;Goodbye!&lt;/p&gt;</pre><p>In this example, only “Hello!” and “Goodbye!” are displayed by default.</p><p>So there are different terms talked while taking about ng-template for eg : TemplateRef , template variable , ngTemplateOutlet and ViewContainerRef , which is quite confusing let’s understand them :</p><h3>TemplateRef</h3><p>&lt;ng-template&gt; elements are represented as instances of the TemplateRef class. To add copies of a template to the DOM, pass a TemplateRef object to the ViewContainerRef method createEmbeddedView().</p><h3>Template Variables</h3><p>You can reference &lt;ng-template&gt; elements using standard template variables. For instance, &lt;ng-template&gt; elements can be used in conjunction with directives like ngTemplateOutlet or as ngIf else clauses.</p><h3>Getting a Reference to a Template Fragment</h3><p>You can obtain a reference to a template fragment in one of three ways:</p><ol><li>Declaring a template reference variable on the &lt;ng-template&gt; element.</li><li>Querying for the fragment using a component or directive query.</li><li>Injecting the fragment in a directive applied directly to the &lt;ng-template&gt; element.</li></ol><p>In all cases, the fragment is represented by a TemplateRef object.</p><h4>1. Referencing with a Template Reference Variable</h4><pre>&lt;p&gt;Static text&lt;/p&gt;<br>&lt;ng-template #greetingTemplate&gt;<br>  &lt;p&gt;Dynamic content&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p>You can now reference this fragment anywhere else in the template using the variable greetingTemplate.</p><h4>2. Referencing with Queries</h4><p>If your template contains fragments, you can query for them using Angular’s @ViewChild or @ViewChildren decorators. For example:</p><pre>@Component({<br>  template: `<br>    &lt;p&gt;Static content&lt;/p&gt;<br>    &lt;ng-template #templateOne&gt;<br>      &lt;p&gt;First fragment&lt;/p&gt;<br>    &lt;/ng-template&gt;<br>    &lt;ng-template #templateTwo&gt;<br>      &lt;p&gt;Second fragment&lt;/p&gt;<br>    &lt;/ng-template&gt;<br>  `,<br>})<br>export class ComponentWithTemplate {<br>  @ViewChild(&#39;templateOne&#39;, { read: TemplateRef }) templateOne: TemplateRef&lt;unknown&gt; | undefined;<br>  @ViewChild(&#39;templateTwo&#39;, { read: TemplateRef }) templateTwo: TemplateRef&lt;unknown&gt; | undefined;<br>}</pre><h4>3. Injecting a Template Fragment</h4><p>You can also inject a template fragment in a directive:</p><pre>@Directive({<br>  selector: &#39;[customDirective]&#39;<br>})<br>export class CustomDirective {<br>  private fragment = inject(TemplateRef);<br>}</pre><pre>&lt;ng-template customDirective&gt;<br>  &lt;p&gt;Custom directive content&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><h3>Rendering a Template Fragment</h3><p>Once you have a TemplateRef object, you can render it in two ways: using the NgTemplateOutlet directive or the ViewContainerRef API.</p><h3>1. Using NgTemplateOutlet</h3><p>You can use NgTemplateOutlet to render templates dynamically:</p><pre>&lt;p&gt;Static content&lt;/p&gt;<br>&lt;ng-template #infoTemplate&gt;<br>  &lt;p&gt;Dynamic section&lt;/p&gt;<br>&lt;/ng-template&gt;<br>&lt;ng-container *ngTemplateOutlet=&quot;infoTemplate&quot;&gt;&lt;/ng-container&gt;</pre><p>This produces the following DOM:</p><pre>&lt;p&gt;Static content&lt;/p&gt;<br>&lt;p&gt;Dynamic section&lt;/p&gt;</pre><h4>Example with @Input Property</h4><p>You can use NgTemplateOutlet with input properties to dynamically pass data:</p><pre>&lt;ng-template #nameTemplate let-userName&gt;<br>  &lt;p&gt;Hello, {{ userName }}!&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><pre>&lt;ng-container *ngTemplateOutlet=&quot;nameTemplate; context: { $implicit: &#39;Developer&#39; }&quot;&gt;&lt;/ng-container&gt;</pre><p>let-userName declares a local template variable (userName) that will receive a value from the context.</p><p>Output:</p><pre>&lt;p&gt;Hello, Developer!&lt;/p&gt;</pre><h3>2. Using ViewContainerRef</h3><p>You can programmatically render templates using ViewContainerRef:</p><pre>@Component({<br>  selector: &#39;dynamic-component&#39;,<br>  template: `<br>    &lt;h3&gt;Dynamic Template Example&lt;/h3&gt;<br>    &lt;ng-template #dynamicTemplate&gt;<br>      &lt;p&gt;Content loaded dynamically&lt;/p&gt;<br>    &lt;/ng-template&gt;<br>    &lt;render-outlet [templateRef]=&quot;dynamicTemplate&quot;&gt;&lt;/render-outlet&gt;<br>  `,<br>})<br>export class DynamicComponent { }</pre><pre>@Component({<br>  selector: &#39;render-outlet&#39;,<br>  template: `&lt;button (click)=&quot;loadTemplate()&quot;&gt;Render&lt;/button&gt;`<br>})<br>export class RenderOutlet {<br>  private viewContainer = inject(ViewContainerRef);<br>  @Input() templateRef: TemplateRef&lt;unknown&gt; | undefined;<br>  loadTemplate() {<br>    if (this.templateRef) {<br>      this.viewContainer.createEmbeddedView(this.templateRef);<br>    }<br>  }<br>}</pre><h3>Conclusion</h3><p>The &lt;ng-template&gt; element is a powerful tool for creating reusable and dynamic templates in Angular. By understanding its usage with TemplateRef, NgTemplateOutlet, and ViewContainerRef, you can unlock advanced templating capabilities in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1875f10b13fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Subscription Management in Angular 16+ with takeUntilDestroyed and dest]]></title>
            <link>https://medium.com/@prashantsaransingh/effortless-subscription-management-in-angular-16-with-takeuntildestroyed-and-dest-32fdca26eb0a?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/32fdca26eb0a</guid>
            <category><![CDATA[ngondestroy]]></category>
            <category><![CDATA[takeuntildestroyed]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ondestroy]]></category>
            <category><![CDATA[destroyref]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 07:53:30 GMT</pubDate>
            <atom:updated>2024-12-04T16:08:50.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Effortless Subscription Management in Angular 16+ with takeUntilDestroyed and DestroyRef</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mYthagS1ok9oL1JqazAiQ.jpeg" /><figcaption>Ai generated image</figcaption></figure><p>In Angular, managing subscriptions effectively is crucial to avoid memory leaks. Traditionally, developers relied on manual subscription cleanup techniques like implementing OnDestroy and unsubscribing in the ngOnDestroy lifecycle. However, these approaches introduced significant boilerplate code and reduced readability.</p><p>Angular 16 introduces a game-changing feature: the takeUntilDestroyed operator. This new approach simplifies subscription management by automating cleanup, enhancing both developer productivity and code clarity.</p><blockquote>Old way : using the ngOnDestroy lifecycle hook:</blockquote><p>We are familiar with closing subscriptions manually in ngOnDestroy. Let&#39;s explore the drawbacks of this approach:</p><pre>export class ExampleComponent implements OnInit, OnDestroy {<br>// Subscriptions to manage<br>private subscription1: Subscription;<br>private subscription2: Subscription;<br><br>  // Injected services<br>  private dataService = inject(DataService);<br><br>  constructor() {<br>    // Subscribe to Router events and store the subscription<br>    this.subscription1 = this.dataService.getValue.subscribe(event =&gt;<br>      console.log(&#39;Router event:&#39;, event)<br>    );<br>  }<br><br>  ngOnInit() {<br>    // Subscribe to DataService observable and store the subscription<br>    this.subscription2= this.dataService.getData.subscribe(data =&gt;<br>      console.log(&#39;Received data:&#39;, data)<br>    );<br>  }<br><br>  ngOnDestroy() {<br>    // Unsubscribe from all subscriptions<br>    this.subscription1.unsubscribe();<br>    this.subscription2.unsubscribe();<br>  }<br>}</pre><blockquote>New way : by using <strong>DestroyRef</strong></blockquote><p>angular introduced DestroyRef API after Angular16 which provides a modern way to manage resources during the destruction of a component or directive. With DestroyRef, you can register a callback to automatically clean up resources when the component is destroyed.</p><p>Syntax :</p><pre>// inject DestroyRef<br>const destroyRef = inject(DestroyRef);<br>// register a destroy callback<br>const unregisterFn = destroyRef.onDestroy(() =&gt; doSomethingOnDestroy());<br>// stop the destroy callback from executing if needed<br>unregisterFn();</pre><p>Let’s take a look at the same example and see how we can use DestroyRef to simplify subscription management:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { inject, DestroyRef } from &#39;@angular/core&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-example&#39;,<br>  template: `&lt;p&gt;Example component&lt;/p&gt;`,<br>})<br>export class ExampleComponent implements OnInit {<br><br>  // Injected services<br>  private dataService = inject(DataService);<br>  private destroyRef = inject(DestroyRef);<br><br>  // Subscriptions<br>  private subscription1: Subscription;<br>  private subscription2: Subscription;<br><br><br>  ngOnInit() {<br><br>    this.subscription1 = this.dataService.getVaue.subscribe(event =&gt;<br>    );<br>    this.subscription2 = this.dataService.getData.subscribe(data =&gt;<br>    );<br><br>    // Cleanup logic for subscription2<br>    this.destroyRef.onDestroy(() =&gt; {<br>      this.subscription2.unsubscribe();<br>      this.subscription1.unsubscribe();<br>    });<br>  }<br>}</pre><p>The problem with above two approaches :</p><ul><li>Every subscription requires a Subscription object to store it.</li><li>The unsubscription logic in ngOnDestroy or destroyRef.onDestroy adds repetitive boilerplate code.</li><li>This makes the code less concise and harder to read, especially in components with multiple subscriptions.</li></ul><p>For most use cases, the new approach of injecting DestroyRef simplifies cleanup compared to implementing the OnDestroy interface. However, when working with <strong>RxJS</strong>, there’s an even more efficient solution:</p><blockquote>One common solution is using the <strong>takeUntil </strong>operator with a <strong>Subject</strong>:</blockquote><p>Before using takeUntil let’s have a look what it is :</p><p>takeUntil: emits the values emitted by the source Observable until a notifier Observable emits a value. to know more of it you can visit :</p><p><a href="https://medium.com/@steven.boyd-thompson/rxjs-operators-takeuntil-4cab871638c2">RxJS Operators: takeUntil</a></p><pre>export class Component implements OnInit, OnDestroy {<br>   data: any; // Variable to hold the data received from the service<br><br>  // Subject used to signal when the observable should complete<br>  private subject = new Subject&lt;void&gt;();<br><br>  // Inject DestroyRef to handle cleanup during the component&#39;s lifecycle<br>  private destroyRef = inject(DestroyRef);<br><br>  constructor(private service: DataService) {}<br><br>  ngOnInit(): void {<br>    // Subscribe to the observable returned by the service<br>    this.service.getData()<br>      .pipe(<br>        takeUntil(this.subject) // Automatically unsubscribes when the subject emits/notify<br>      )<br>      .subscribe(response =&gt; {<br>        // Assign the response data to the &#39;data&#39; variable<br>        this.data = response;<br>      });<br><br>    // Register cleanup logic with DestroyRef<br>    this.destroyRef.onDestroy(() =&gt; {<br>      // Signal completion to terminate the observable<br>      this.subject.next();<br>      this.subject.complete();<br>    });<br>  }<br>}</pre><p>While effective, this approach requires extra code:</p><ul><li>Declaring and managing a Subject.</li><li>Manually emitting next and completing the Subject in ngOnDestroy.</li></ul><blockquote>The Star Feature: <strong>takeUntilDestroyed</strong></blockquote><p>The takeUntilDestroyed operator, introduced in Angular 16, takes subscription management to the next level. It automatically detects and ties into the component&#39;s destruction lifecycle, eliminating the need for manual cleanup or intermediate Subjects.</p><p>Basically, <em>takeUntilDestroyed</em> completes the Observable when the calling context (component, directive, service, etc) is destroyed.</p><pre>import { takeUntilDestroyed } from &#39;@angular/core/rxjs-interop&#39;;<br><br>export class Component implements OnInit {<br>  data: any;<br><br>  constructor(private service: DataService) {<br>    this.service.getData()<br>      .pipe(takeUntilDestroyed())<br>      .subscribe(response =&gt; this.data = response);<br>  }<br>}</pre><p><strong>Key Benefits:</strong></p><ul><li>No manual Subject management.</li><li>Cleaner, more readable code.</li><li>Automatically integrates with the component’s destruction lifecycle.</li></ul><blockquote>Advanced Use Case: Passing <strong>OnDestroy </strong>Reference</blockquote><p>In scenarios where one component’s lifecycle depends on another (e.g., a parent and child component), DestroyRef enables seamless communication between their destruction lifecycles.</p><p>Child Component :</p><pre>import { inject, DestroyRef } from &#39;@angular/core&#39;;<br><br>export class ChildComponent {<br>  destroyRef = inject(DestroyRef);<br>}</pre><p>Parent Component :</p><pre>import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;<br>import { interval } from &#39;rxjs&#39;;<br>import { takeUntilDestroyed } from &#39;@angular/core/rxjs-interop&#39;;<br>import { ChildComponent } from &#39;./child.component&#39;;<br><br>export class Parent implements OnInit {<br>  // Access the child component instance using ViewChild<br>  @ViewChild(ChildComponent) child!: ChildComponent;<br><br>  ngOnInit(): void {<br>    interval(1000)<br>      .pipe(<br>        // Automatically unsubscribe when the child component is destroyed<br>        takeUntilDestroyed(this.child.destroyRef)<br>      )<br>      .subscribe(count =&gt; {<br>        console.log(count);<br>      });<br>  }<br>}</pre><p>Here, the parent component’s subscription will remain active only as long as the child component exists.</p><p>Angular 16’s takeUntilDestroyed and DestroyRef streamline subscription management by:</p><ul><li>Reducing boilerplate code.</li><li>Enhancing readability.</li><li>Minimizing the risk of memory leaks.</li></ul><p>Whether you’re handling subscriptions in standalone components or managing complex parent-child relationships, these features make Angular development more efficient and enjoyable.</p><p>Adopt takeUntilDestroyed today and experience cleaner, safer, and more maintainable Angular code!</p><p><em>Was this article useful to you? I’d love to hear your feedback! Hit me up on </em><a href="https://x.com/PrashantSaranS3"><em>Twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32fdca26eb0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subject Vs BehaviourSubject Vs ReplaySubject]]></title>
            <link>https://medium.com/@prashantsaransingh/subject-vs-behavioursubject-vs-replaysubject-e33278c98647?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/e33278c98647</guid>
            <category><![CDATA[subject]]></category>
            <category><![CDATA[replaysubject]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[behaviour-subject]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 10:26:24 GMT</pubDate>
            <atom:updated>2024-12-03T11:44:51.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwjM73tp8gzxUSEmEczPzA.jpeg" /><figcaption>Ai generated Image</figcaption></figure><p>Reactive programming in JavaScript often requires handling asynchronous data streams, which is where <strong>RxJS</strong> comes in. At the heart of RxJS are <strong>Subjects</strong>, a versatile tool for multicasting data to multiple observers. Among the types of Subjects, three commonly used ones are <strong>Subject</strong>, <strong>BehaviorSubject</strong>, and <strong>ReplaySubject</strong>.</p><p>In this article, we’ll explore these types, their unique features, use cases, and examples to understand when and why to use each.</p><p>Here’s a rough idea of the inheritance from the RxJS source code:</p><ul><li><strong>Subject</strong> extends Observable and adds the ability to emit values (next, error, complete).</li><li><strong>BehaviorSubject</strong> extends Subject and adds logic to store and replay the last emitted value.</li><li><strong>ReplaySubject</strong> also extends Subject, just like BehaviorSubject. However, it adds additional functionality to replay a specified number of emitted values (or values emitted within a certain time window) to new subscribers.</li></ul><p>Here’s how it fits into the inheritance hierarchy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*1tXkwPMS_xNjxv490mBVzQ.png" /></figure><blockquote><strong>Subject</strong></blockquote><p>A <strong>Subject</strong> is both an <strong>Observable</strong> and an <strong>Observer</strong>. This means:</p><ul><li>It can be subscribed to like any other Observable.</li><li>It can emit values to its subscribers using methods like next, error, or complete.</li></ul><p>Unlike a plain Observable that emits values to one subscriber, a <strong>Subject</strong> allows multicasting values to multiple subscribers simultaneously.</p><p>Key Features:</p><ol><li><strong>No Initial Value</strong>: A Subject does not hold or replay any previous values.</li><li><strong>Multicasting</strong>: Multiple subscribers share the same Subject and receive the same emitted values.</li><li><strong>Real-Time Streaming</strong>: Subscribers only receive values emitted after they subscribe.</li></ol><p>Example :</p><pre>import { Subject } from &#39;rxjs&#39;;<br><br>const subject = new Subject(); // no initial value<br><br>subject.subscribe(value =&gt; console.log(&#39;Subscriber 1:&#39;, value));<br><br><br>subject.next(1); // Subscriber 1: 1<br>subject.next(2); // Subscriber 1: 2<br><br>subject.subscribe(value =&gt; console.log(&#39;Subscriber 2:&#39;, value));<br><br>subject.next(3);<br>// Subscriber 1: 3<br>// Subscriber 2: 3</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*5swwjsCmSO9IfsL77ACtiA.png" /></figure><blockquote><strong>Behaviour Subject</strong></blockquote><p>A <strong>BehaviorSubject</strong> is a specialized type of Subject that holds a <strong>current value</strong>. Unlike a plain Subject, new subscribers immediately receive the most recent value, making it perfect for state management.</p><p>Key Features:</p><ol><li><strong>Initial Value</strong>: Requires an initial value upon creation.</li><li><strong>Replays the Last Value</strong>: New subscribers receive the most recent value, even if they subscribe after emissions have started.</li><li><strong>Stores State</strong>: It can act as a state container in reactive applications.</li></ol><pre>import { BehaviorSubject } from &#39;rxjs&#39;;<br><br>const behaviorSubject = new BehaviorSubject(0); // Initial value is 0<br><br>behaviorSubject.subscribe(value =&gt; console.log(&#39;Subscriber 1:&#39;, value));<br>// Subscriber 1: 0 (recieves initial value)<br><br>behaviorSubject.next(1); // Subscriber 1: 1<br>behaviorSubject.next(2); // Subscriber 1: 2<br><br>behaviorSubject.subscribe(value =&gt; console.log(&#39;Subscriber 2:&#39;, value));<br>// Subscriber 2: 2 (gets the most recent value)<br><br>behaviorSubject.next(3);<br>// Subscriber 1: 3<br>// Subscriber 2: 3</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*ty17dovxKMTlRt9gQgqq5w.png" /></figure><blockquote><strong>Replay Subject</strong></blockquote><p>A <strong>ReplaySubject</strong> stores a <strong>buffer of emitted values</strong> and replays them to new subscribers. You can configure the number of values it stores and replays, as well as an optional time window.</p><p><strong>Key Features</strong>:</p><ol><li><strong>Replays Multiple Values</strong>: New subscribers receive all buffered values, up to the configured limit.</li><li><strong>Configurable Buffer Size</strong>: Controls how many past values are stored.</li><li><strong>Optional Time Window</strong>: Limits values based on how recently they were emitted.</li></ol><pre>import { ReplaySubject } from &#39;rxjs&#39;;<br><br>const replaySubject = new ReplaySubject(2); // Buffer size of 2<br><br>// Emit some values<br>replaySubject.next(1);<br>replaySubject.next(2);<br>replaySubject.next(3); // Only the last 2 values (2, 3) will be replayed<br><br>// Subscriber 1<br>replaySubject.subscribe(value =&gt; console.log(&#39;Subscriber 1:&#39;, value)); <br>// Subscriber 1: 2<br>// Subscriber 1: 3<br><br>// Emit another value<br>replaySubject.next(4); <br>// Subscriber 1: 4<br><br>// Subscriber 2 (subscribes later)<br>replaySubject.subscribe(value =&gt; console.log(&#39;Subscriber 2:&#39;, value)); <br>// Subscriber 2: 3<br>// Subscriber 2: 4</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*fSWk8aZE1jOcajORJlx0EA.png" /></figure><pre>import { ReplaySubject } from &#39;rxjs&#39;;<br><br>const replaySubject = new ReplaySubject(0, 2000); // Time window of 2000ms (2 seconds)<br><br>// Emit some values at different times<br>replaySubject.next(1); // Emitted at time = 0ms<br>setTimeout(() =&gt; replaySubject.next(2), 1000); // Emitted at time = 1000ms<br>setTimeout(() =&gt; replaySubject.next(3), 3000); // Emitted at time = 3000ms<br><br>// Subscriber 1 subscribes at time = 4000ms<br>setTimeout(() =&gt; {<br>  console.log(&#39;Subscriber 1 subscribes:&#39;);<br>  replaySubject.subscribe(value =&gt; console.log(&#39;Subscriber 1:&#39;, value));<br>}, 4000);<br><br>// Emit another value at time = 5000ms<br>setTimeout(() =&gt; replaySubject.next(4), 5000);<br><br>// Subscriber 2 subscribes at time = 6000ms<br>setTimeout(() =&gt; {<br>  console.log(&#39;Subscriber 2 subscribes:&#39;);<br>  replaySubject.subscribe(value =&gt; console.log(&#39;Subscriber 2:&#39;, value));<br>}, 6000);</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*RUaix9Xr8tUGUpWXBIJyWg.png" /></figure><p><strong>Subscriber 1 (at 4000ms)</strong>:</p><ul><li>The time window is 2000ms.</li><li>Only values emitted after 2000ms are within the time window (3).</li></ul><p><strong>Subscriber 2 (at 6000ms)</strong>:</p><ul><li>The time window is still 2000ms.</li><li>Only values emitted after 4000ms are within the time window (4).</li></ul><p>so ,Subject is a basic observer that doesn&#39;t retain values, emitting only to active subscribers. BehaviorSubject stores the most recent value and immediately replays it to new subscribers, making it ideal for state management. ReplaySubject retains a buffer of past values or uses a time window to replay them to new subscribers, useful for event history or logging. Choose Subject for simple event streams, BehaviorSubject for maintaining a current state, and ReplaySubject for replaying past events to late subscribers. Each has a distinct role in managing reactive data streams.</p><p><em>Was this article useful to you? I’d love to hear your feedback! Hit me up on </em><a href="https://x.com/PrashantSaranS3"><em>Twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e33278c98647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[using signals with Services in angular]]></title>
            <link>https://medium.com/@prashantsaransingh/using-signals-with-services-in-angular-b153e957873d?source=rss-4159ccff2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/b153e957873d</guid>
            <category><![CDATA[services-in-angular]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[angular-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-18]]></category>
            <dc:creator><![CDATA[Prashantsaransingh]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 17:13:17 GMT</pubDate>
            <atom:updated>2024-11-13T19:58:00.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*YmGphQeZ7dBSY8S4K0K2FQ.jpeg" /></figure><p>Angular Signals are a new reactive state management feature in Angular v16+. They provide a more efficient and intuitive way to manage state and trigger updates in your components. Signals are essentially reactive variables that wrap a value and notify interested consumers when that value changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*w4HMkaeMLwm-8JjxpqnFHg.jpeg" /></figure><blockquote><strong>Declaring a Signal in a Service</strong></blockquote><p>To declare a signal in a service, you can use the signal function from the @angular/core library. This function returns a signal object, which holds the current value of the signal and provides methods to update and subscribe to changes.</p><p>Syntax :</p><pre>const defaultValue=0;<br>const count = signal(defaultValue);<br>console.log(&#39;The count is: &#39; + count()); // The count is: 0</pre><p><strong>Example:</strong></p><pre><br>import { Injectable, signal } from &#39;@angular/core&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class OperationService {<br>  totalSum = signal&lt;number&gt;(0);<br><br>  calculateSum(num1: number, num2: number) {<br>    this.totalSum.set(num1 + num2);<br>  }<br>}</pre><p>In this example, totalSum is a signal that holds the calculated sum. The calculateSum function updates the signal&#39;s value.</p><blockquote><strong>Using Signals in Components</strong></blockquote><p>While you can directly access signals in components, it is generally recommended to use the computed function or the asReadOnly method</p><p>as it does not return writable signal i.e., it can be only fetched but can’t be changed from component</p><blockquote><strong>Using computed Function :</strong></blockquote><pre>import { Component, computed, inject } from &#39;@angular/core&#39;;<br><br><br>@Component({<br>  selector: &#39;app-my-component&#39;,<br>  template: `<br>    &lt;p&gt;The sum is: {{ result }}&lt;/p&gt;<br>  `<br>})<br>export class MyComponent {<br>  private opService = inject(OperationService);<br>  result = computed(() =&gt; this.opService.totalSum());<br>}</pre><p>The computed function creates a derived signal that re-evaluates whenever the totalSum signal changes. This ensures that the result is always up-to-date.</p><blockquote><strong>Using </strong><strong>asReadOnly Method:</strong></blockquote><pre>import { Component, inject } from &#39;@angular/core&#39;;<br><br><br>@Component({<br>  selector: &#39;app-my-component&#39;,<br>  template: `<br>    &lt;p&gt;The sum is: {{ result }}&lt;/p&gt;<br>  `<br>})<br>export class MyComponent {<br>  private opService = inject(OperationService);<br>  result = this.opService.totalSum().asReadOnly();<br>}</pre><p>The asReadOnly method returns a read-only version of the signal, preventing accidental modifications outside the service.</p><p>To provide controlled access to the totalSum signal, we can create a public getter function:</p><pre>import { Injectable, signal } from &#39;@angular/core&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class OperationService {<br>  private _totalSum = signal&lt;number&gt;(0);<br><br>  get totalSum() {<br>    return this._totalSum.asReadOnly();<br>  }<br><br>  calculateSum(num1: number, num2: number) {<br>    this._totalSum.set(num1 + num2);<br>  }<br>}</pre><p>here, The _totalSum signal is declared as private to encapsulate the state within the service.</p><p>Now, public totalSum getter returns a read-only view of the _totalSum signal using asReadOnly(). This prevents accidental modifications to the signal&#39;s value from outside the service.</p><p>By declaring _totalSum as private and providing a public getter, you&#39;re effectively encapsulating the service&#39;s state. The asReadOnly() method ensures that external components can only observe the signal&#39;s value, preventing unintended modifications.</p><p>This approach promotes:</p><ul><li><strong>Encapsulation:</strong> The internal state of the service is protected.</li><li><strong>Controlled State Updates:</strong> The calculateSum method is the sole mechanism for updating the _totalSum signal.</li><li><strong>Read-Only Access:</strong> External components can only observe the signal’s value, ensuring data integrity.</li></ul><p><strong>Advantages of Using Signals in Services:</strong></p><ul><li><strong>Reactive and Efficient:</strong> Signals automatically update components when their values change, eliminating the need for manual updates and improving performance.</li><li><strong>Immutability:</strong> Using asReadOnly ensures that the signal&#39;s value cannot be changed from outside the service, promoting data integrity and avoiding unintended side effects.</li><li><strong>Simplified State Management:</strong> Signals provide a clear and concise way to manage state within your application, making your code more readable and maintainable.</li></ul><p>By effectively utilizing signals in your Angular services, you can build more robust, responsive, and scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b153e957873d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>