<?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 Amit Dubey on Medium]]></title>
        <description><![CDATA[Stories by Amit Dubey on Medium]]></description>
        <link>https://medium.com/@amit.dubey01?source=rss-b0ad97456df7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UlCw3VAHmqEYaZVLFilcIw.jpeg</url>
            <title>Stories by Amit Dubey on Medium</title>
            <link>https://medium.com/@amit.dubey01?source=rss-b0ad97456df7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:34:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amit.dubey01/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 Signals]]></title>
            <link>https://medium.com/globant/angular-signals-13305d83ba0d?source=rss-b0ad97456df7------2</link>
            <guid isPermaLink="false">https://medium.com/p/13305d83ba0d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[change-detection-strategy]]></category>
            <dc:creator><![CDATA[Amit Dubey]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 13:02:08 GMT</pubDate>
            <atom:updated>2024-11-05T13:02:08.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhancing Reactivity and Change Detection Control</h4><figure><img alt="Angular Signals" src="https://cdn-images-1.medium.com/max/1024/0*rsQOL9KzxHfseCEq" /><figcaption>Photo by <a href="https://unsplash.com/@theyshane">Shane</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Have you ever found yourself in a situation where you had to recalculate values manually? Or traverse the whole component tree just because a single value changed? It’s time to say goodbye to re-computation and tedious tasks and welcome the efficiency of signals.</p><p>Imagine this scenario: you have a code snippet. In which you have a property called value3. This value3 calculates the sum of value1 and value2 with calculateValue3(). Now, if value1 is updated, then you need to recalculate value3 by calling calculateValue3() again. It’s a repetitive and time-consuming process.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-without-signals&#39;,<br>  standalone: true,<br>  imports: [],<br>  templateUrl: &#39;./without-signals.component.html&#39;,<br>  styleUrl: &#39;./without-signals.component.scss&#39;<br>})<br>export class WithoutSignalsComponent implements OnInit {<br>  value1 = 50;<br>  value2 = 50;<br><br>  value3!: number;<br><br>  ngOnInit(): void {<br>    this.calculateValue3();<br>  }<br><br>  calculateValue3() {<br>    this.value3 = this.value1 + this.value2;<br>  }<br><br>  changesValue1() {<br>    this.value1 += 75;<br>    // Need to call calculateValue3() again to assign updated value to value3<br>  }<br>}</pre><p>But with <a href="https://angular.dev/api/core/signal">signals</a>, this hassle becomes history. Signals update dependent values, like value3 , automatically. They update when any related values, such as value1 or value2 , change.</p><figure><img alt="Shows the difference when a value is changed and how it is calculated" src="https://cdn-images-1.medium.com/max/826/0*kfOHE6dvugAPHPET" /><figcaption><em>Shows the difference when a value is changed and how it is calculated</em></figcaption></figure><p>As shown in the animated image above, on the left section when we update the value1 value by adding 75 to it everytime when we click the button, the value of value3 is not updating but with signals on the right section, its updated automatically.</p><p>Let’s take a step further and consider a more complex example. Picture a system that has seven interconnected components, each tied together through parent-child relationships. In a Default <a href="https://angular.dev/api/core/ChangeDetectionStrategy">change detection strategy</a>, modifying the value of a single component triggers a cascade effect, marking the entire component tree as dirty. And if it’s a OnPush change detection strategy, even the parents are marked as dirty.</p><p>However, with signals, only the relevant components or those sharing the same signals are notified, saving you valuable resources and processing time.</p><p>The image below shows components, some of them with children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkl1qQYQN7MDcaYmIU8tKg.png" /><figcaption>Nested components listed in a binary structure</figcaption></figure><p>Now, when we update the bound value of the last component, i.e., Component 7 to value as 8 its parent components i.e., component 3 and component 1 are marked as dirty or checked for change detection for the OnPush strategy when signals are not used.</p><p>Notice the node color change. Each time the component is checked for change detection, the node’s color is updated to red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFrbqcLCfuA6_72VKAdRgw.png" /><figcaption><em>Shows the difference when a last node value is changed and which components are marked dirty</em></figcaption></figure><p>However, with signals, only the component is marked as dirty or checked for change detection where the signal value is bound. That is why the color of the nodes of parent components, i.e., component 3 and component 1 are not changed.</p><h3>Why Signals?</h3><p>Now, let’s address the question on everyone’s mind: why signals?</p><ul><li>Reactivity: Signals provide a highly responsive environment for your components. Whenever a signal’s value changes, it automatically notifies the consumer, ensuring real-time updates without any additional effort. It’s like having a personal assistant that keeps you informed of every little change so you can focus on the important stuff, like deciding what to have for lunch!</li><li>Change Detection Control: Signals give you enhanced control over change detection. By selectively notifying only the relevant components, you optimize performance and avoid unnecessary recalculations or traversals, sparing you from the chaos of unnecessary updates.</li></ul><h3>What are signals?</h3><p>So, what exactly are signals?</p><p>At their core, signals are values with built-in notification capabilities. They follow the producer-consumer pattern. The consumer immediately receives any change made by the producer. It’s like having a secret telepathic connection between your variables!</p><p>Creating a signal is simple. You define a variable and assign a signal function to it. The signal function requires an initial value. This lets you pass in the desired value when assigning it to a variable. It’s like giving birth to a little signal baby and watching it grow!</p><p>For example, consider the following snippet:</p><pre>myFirstSignal = signal&lt;string&gt;(&#39;Signal&#39;);</pre><p>In this case, the type &lt;string&gt; is explicitly attached to the signal function. Although it’s not required because TypeScript can infer the type from the assigned value, it’s good practice to define the type explicitly.</p><p>Alternatively, for cases where the type cannot be inferred from the value, it’s essential to assign the type explicitly, as demonstrated in the example below:</p><pre>employee = signal&lt;IEmployee&gt;({<br>  name: &#39;John&#39;,<br>  age: 25<br>});</pre><p>All signals must have an initial value as the first parameter of the signal function is required. If the initial value is not provided then there will be a compile-time error stating: An argument for ‘initialValue’ was not provided. This allows for consistent behavior and smooth operation. It’s like giving your signal a head start in the race of reactivity!</p><p>You can create a read-only signal by using asReadonly() function after the signal function invocation.</p><pre>readOnlySignal = signal&lt;string&gt;(&#39;Only read me&#39;).asReadonly();</pre><p>Signals can be defined anywhere within your Angular application, including <a href="https://angular.dev/api/core/Component">components</a>, <a href="https://angular.dev/api/core/Directive#">directives</a>, or <a href="https://angular.dev/tutorials/first-app/09-services/">services</a>. They offer flexibility and can adapt to your specific needs.</p><h3>Read signals</h3><p>Once you’ve defined a signal using the signal() function, you can access its value by simply calling the variable as a function.</p><pre>myFirstSignal();</pre><p>You can also read the signal value directly in your template:</p><pre>&lt;p&gt;{{ myFirstSignal() }}&lt;/p&gt;</pre><h3>Update signals</h3><p>Updating signals is more simple. Signals provide methods to update signal variable values. One of the methods is set .</p><pre>set(value: T): void</pre><p>set replaces the signal’s old value with an updated new value passed as a parameter and notifies the dependents. Example:</p><pre>myFirstSignal = signal&lt;string&gt;(&#39;Signal&#39;);<br><br>ngOnInit(): void {<br>  this.myFirstSignal.set(&#39;Signal Updated&#39;);<br>}</pre><p>Another method is update .</p><pre>update(updateFn: (value: T) =&gt; T)</pre><p>update changes the value of the signal based on its previous value. It takes a function as a parameter that has access to the current signal value. Example:</p><pre>myFirstSignal = signal&lt;string&gt;(&#39;Signal&#39;);<br><br>ngOnInit(): void {<br>  this.myFirstSignal.update((currentValue: string) =&gt; currentValue + &#39; Updated&#39;);<br>}</pre><blockquote>Note that these methods will not be applicable if the signal is read only.</blockquote><h3>Computed signals</h3><p>As we saw in our previous example, we created value3 based on the values of value1 and value2. That’s what computed signals are. Computed signals are signals that depend on other signal values. It takes a function as a parameter which returns a computed value.</p><p>To create a computed signal:</p><pre>value3!: Signal&lt;number&gt;;</pre><p>Then you can assign a value to it by calling the computed function of the signal.</p><pre>this.value3 = computed(() =&gt; this.value1() + this.value2());</pre><h3>Effect</h3><p>If you have created signals and if you want to observe the signal changes, then you need an effect. Effects are called whenever there is a change in the signal value it is looking for. In essence, it invokes side effects.</p><pre>effect(() =&gt; {<br>  console.log(&#39;Changed value3&#39;, this.value3());<br>})</pre><p>An effect should be written inside the <a href="https://angular.dev/guide/di/dependency-injection-context">injection context</a>. Example: constructor of your component.</p><p>Remember that you cannot set or update any signal value inside an effect. The code below will throw an error at runtime.</p><pre>effect(() =&gt; {<br>  this.value1.set(345);<br>  console.log(&#39;Changed value3&#39;, this.value3());<br>});</pre><p>This can be achieved by using allowSignalWrites as a second parameter of effect.</p><pre>effect(() =&gt; {<br>  this.value1.set(345);<br>  console.log(&#39;Changed value3&#39;, this.value3());<br>}, { allowSignalWrites: true });</pre><p>Effect uses DestroyRef under the hood, which automatically stops or unsubscribes it whenever a component is destroyed.</p><p>This behavior can be changed using manualCleanup as another property of the object for the second parameter which tells Angular that this effect needs manual clean-up and should not be automatically removed from the memory.</p><pre>this.trackEffect = effect(() =&gt; {<br>  console.log(&#39;Changed value3&#39;, this.value3());<br>}, { manualCleanup: true });</pre><p>Once manualCleanup is added to the effect, destroy function should be called in the ngOnDestroy lifecycle hook to remove it from the memory.</p><pre>ngOnDestroy(): void {<br>  this.trackEffect.destroy();<br>}</pre><h3>Conclusion</h3><p>Signals empower you to create a dynamic and efficient application, where changes propagate effortlessly, and control over change detection lies in your hands.</p><p>Embrace the power of signals and witness the transformation in your development process. Say goodbye to unnecessary recalculations and unnecessary traversals, and welcome a new era of reactivity and change detection control.</p><h3>More Readings</h3><p><a href="https://www.freecodecamp.org/news/angular-signals/">Signals in Angular - How to Write More Reactive Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13305d83ba0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/angular-signals-13305d83ba0d">Angular Signals</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>